babylon.max.js 3.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. if (this.x !== this.y) {
  1403. return true;
  1404. }
  1405. if (this.x !== this.z) {
  1406. return true;
  1407. }
  1408. if (this.y !== this.z) {
  1409. return true;
  1410. }
  1411. return false;
  1412. },
  1413. enumerable: true,
  1414. configurable: true
  1415. });
  1416. // Properties
  1417. /**
  1418. * Returns the length of the Vector3 (float).
  1419. */
  1420. Vector3.prototype.length = function () {
  1421. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1422. };
  1423. /**
  1424. * Returns the squared length of the Vector3 (float).
  1425. */
  1426. Vector3.prototype.lengthSquared = function () {
  1427. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1428. };
  1429. // Methods
  1430. /**
  1431. * Normalize the current Vector3.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.normalize = function () {
  1435. var len = this.length();
  1436. if (len === 0 || len === 1.0)
  1437. return this;
  1438. var num = 1.0 / len;
  1439. this.x *= num;
  1440. this.y *= num;
  1441. this.z *= num;
  1442. return this;
  1443. };
  1444. /**
  1445. * Returns a new Vector3 copied from the current Vector3.
  1446. */
  1447. Vector3.prototype.clone = function () {
  1448. return new Vector3(this.x, this.y, this.z);
  1449. };
  1450. /**
  1451. * Copies the passed vector coordinates to the current Vector3 ones.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.copyFrom = function (source) {
  1455. this.x = source.x;
  1456. this.y = source.y;
  1457. this.z = source.z;
  1458. return this;
  1459. };
  1460. /**
  1461. * Copies the passed floats to the current Vector3 coordinates.
  1462. * Returns the updated Vector3.
  1463. */
  1464. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1465. this.x = x;
  1466. this.y = y;
  1467. this.z = z;
  1468. return this;
  1469. };
  1470. /**
  1471. * Copies the passed floats to the current Vector3 coordinates.
  1472. * Returns the updated Vector3.
  1473. */
  1474. Vector3.prototype.set = function (x, y, z) {
  1475. return this.copyFromFloats(x, y, z);
  1476. };
  1477. // Statics
  1478. /**
  1479. *
  1480. */
  1481. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1482. var d0 = Vector3.Dot(vector0, axis) - size;
  1483. var d1 = Vector3.Dot(vector1, axis) - size;
  1484. var s = d0 / (d0 - d1);
  1485. return s;
  1486. };
  1487. /**
  1488. * Returns a new Vector3 set from the index "offset" of the passed array.
  1489. */
  1490. Vector3.FromArray = function (array, offset) {
  1491. if (!offset) {
  1492. offset = 0;
  1493. }
  1494. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1495. };
  1496. /**
  1497. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1498. * This function is deprecated. Use FromArray instead.
  1499. */
  1500. Vector3.FromFloatArray = function (array, offset) {
  1501. return Vector3.FromArray(array, offset);
  1502. };
  1503. /**
  1504. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1505. */
  1506. Vector3.FromArrayToRef = function (array, offset, result) {
  1507. result.x = array[offset];
  1508. result.y = array[offset + 1];
  1509. result.z = array[offset + 2];
  1510. };
  1511. /**
  1512. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1513. * This function is deprecated. Use FromArrayToRef instead.
  1514. */
  1515. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1516. return Vector3.FromArrayToRef(array, offset, result);
  1517. };
  1518. /**
  1519. * Sets the passed vector "result" with the passed floats.
  1520. */
  1521. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1522. result.x = x;
  1523. result.y = y;
  1524. result.z = z;
  1525. };
  1526. /**
  1527. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1528. */
  1529. Vector3.Zero = function () {
  1530. return new Vector3(0.0, 0.0, 0.0);
  1531. };
  1532. /**
  1533. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1534. */
  1535. Vector3.One = function () {
  1536. return new Vector3(1.0, 1.0, 1.0);
  1537. };
  1538. /**
  1539. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1540. */
  1541. Vector3.Up = function () {
  1542. return new Vector3(0.0, 1.0, 0.0);
  1543. };
  1544. /**
  1545. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1546. */
  1547. Vector3.Forward = function () {
  1548. return new Vector3(0.0, 0.0, 1.0);
  1549. };
  1550. /**
  1551. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1552. */
  1553. Vector3.Right = function () {
  1554. return new Vector3(1.0, 0.0, 0.0);
  1555. };
  1556. /**
  1557. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1558. */
  1559. Vector3.Left = function () {
  1560. return new Vector3(-1.0, 0.0, 0.0);
  1561. };
  1562. /**
  1563. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1564. * This method computes tranformed coordinates only, not transformed direction vectors.
  1565. */
  1566. Vector3.TransformCoordinates = function (vector, transformation) {
  1567. var result = Vector3.Zero();
  1568. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1569. return result;
  1570. };
  1571. /**
  1572. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1573. * This method computes tranformed coordinates only, not transformed direction vectors.
  1574. */
  1575. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1576. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1577. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1578. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1579. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1580. result.x = x / w;
  1581. result.y = y / w;
  1582. result.z = z / w;
  1583. };
  1584. /**
  1585. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1586. * This method computes tranformed coordinates only, not transformed direction vectors.
  1587. */
  1588. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1589. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1590. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1591. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1592. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1593. result.x = rx / rw;
  1594. result.y = ry / rw;
  1595. result.z = rz / rw;
  1596. };
  1597. /**
  1598. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1599. * This methods computes transformed normalized direction vectors only.
  1600. */
  1601. Vector3.TransformNormal = function (vector, transformation) {
  1602. var result = Vector3.Zero();
  1603. Vector3.TransformNormalToRef(vector, transformation, result);
  1604. return result;
  1605. };
  1606. /**
  1607. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1608. * This methods computes transformed normalized direction vectors only.
  1609. */
  1610. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1611. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1612. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1613. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1614. result.x = x;
  1615. result.y = y;
  1616. result.z = z;
  1617. };
  1618. /**
  1619. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1620. * This methods computes transformed normalized direction vectors only.
  1621. */
  1622. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1623. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1624. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1625. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1626. };
  1627. /**
  1628. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1629. */
  1630. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1631. var squared = amount * amount;
  1632. var cubed = amount * squared;
  1633. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1634. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1635. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1636. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1637. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1638. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1639. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1640. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1641. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1642. return new Vector3(x, y, z);
  1643. };
  1644. /**
  1645. * 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".
  1646. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1647. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1648. */
  1649. Vector3.Clamp = function (value, min, max) {
  1650. var x = value.x;
  1651. x = (x > max.x) ? max.x : x;
  1652. x = (x < min.x) ? min.x : x;
  1653. var y = value.y;
  1654. y = (y > max.y) ? max.y : y;
  1655. y = (y < min.y) ? min.y : y;
  1656. var z = value.z;
  1657. z = (z > max.z) ? max.z : z;
  1658. z = (z < min.z) ? min.z : z;
  1659. return new Vector3(x, y, z);
  1660. };
  1661. /**
  1662. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1663. */
  1664. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1665. var squared = amount * amount;
  1666. var cubed = amount * squared;
  1667. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1668. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1669. var part3 = (cubed - (2.0 * squared)) + amount;
  1670. var part4 = cubed - squared;
  1671. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1672. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1673. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1674. return new Vector3(x, y, z);
  1675. };
  1676. /**
  1677. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1678. */
  1679. Vector3.Lerp = function (start, end, amount) {
  1680. var result = new Vector3(0, 0, 0);
  1681. Vector3.LerpToRef(start, end, amount, result);
  1682. return result;
  1683. };
  1684. /**
  1685. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1686. */
  1687. Vector3.LerpToRef = function (start, end, amount, result) {
  1688. result.x = start.x + ((end.x - start.x) * amount);
  1689. result.y = start.y + ((end.y - start.y) * amount);
  1690. result.z = start.z + ((end.z - start.z) * amount);
  1691. };
  1692. /**
  1693. * Returns the dot product (float) between the vectors "left" and "right".
  1694. */
  1695. Vector3.Dot = function (left, right) {
  1696. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1697. };
  1698. /**
  1699. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1700. * The cross product is then orthogonal to both "left" and "right".
  1701. */
  1702. Vector3.Cross = function (left, right) {
  1703. var result = Vector3.Zero();
  1704. Vector3.CrossToRef(left, right, result);
  1705. return result;
  1706. };
  1707. /**
  1708. * Sets the passed vector "result" with the cross product of "left" and "right".
  1709. * The cross product is then orthogonal to both "left" and "right".
  1710. */
  1711. Vector3.CrossToRef = function (left, right, result) {
  1712. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1713. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1714. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1715. result.copyFrom(MathTmp.Vector3[0]);
  1716. };
  1717. /**
  1718. * Returns a new Vector3 as the normalization of the passed vector.
  1719. */
  1720. Vector3.Normalize = function (vector) {
  1721. var result = Vector3.Zero();
  1722. Vector3.NormalizeToRef(vector, result);
  1723. return result;
  1724. };
  1725. /**
  1726. * Sets the passed vector "result" with the normalization of the passed first vector.
  1727. */
  1728. Vector3.NormalizeToRef = function (vector, result) {
  1729. result.copyFrom(vector);
  1730. result.normalize();
  1731. };
  1732. Vector3.Project = function (vector, world, transform, viewport) {
  1733. var cw = viewport.width;
  1734. var ch = viewport.height;
  1735. var cx = viewport.x;
  1736. var cy = viewport.y;
  1737. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1738. 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);
  1739. var matrix = MathTmp.Matrix[0];
  1740. world.multiplyToRef(transform, matrix);
  1741. matrix.multiplyToRef(viewportMatrix, matrix);
  1742. return Vector3.TransformCoordinates(vector, matrix);
  1743. };
  1744. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1745. var matrix = MathTmp.Matrix[0];
  1746. world.multiplyToRef(transform, matrix);
  1747. matrix.invert();
  1748. source.x = source.x / viewportWidth * 2 - 1;
  1749. source.y = -(source.y / viewportHeight * 2 - 1);
  1750. var vector = Vector3.TransformCoordinates(source, matrix);
  1751. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1752. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1753. vector = vector.scale(1.0 / num);
  1754. }
  1755. return vector;
  1756. };
  1757. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1758. var matrix = MathTmp.Matrix[0];
  1759. world.multiplyToRef(view, matrix);
  1760. matrix.multiplyToRef(projection, matrix);
  1761. matrix.invert();
  1762. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1763. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1764. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1765. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1766. vector = vector.scale(1.0 / num);
  1767. }
  1768. return vector;
  1769. };
  1770. Vector3.Minimize = function (left, right) {
  1771. var min = left.clone();
  1772. min.MinimizeInPlace(right);
  1773. return min;
  1774. };
  1775. Vector3.Maximize = function (left, right) {
  1776. var max = left.clone();
  1777. max.MaximizeInPlace(right);
  1778. return max;
  1779. };
  1780. /**
  1781. * Returns the distance (float) between the vectors "value1" and "value2".
  1782. */
  1783. Vector3.Distance = function (value1, value2) {
  1784. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1785. };
  1786. /**
  1787. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1788. */
  1789. Vector3.DistanceSquared = function (value1, value2) {
  1790. var x = value1.x - value2.x;
  1791. var y = value1.y - value2.y;
  1792. var z = value1.z - value2.z;
  1793. return (x * x) + (y * y) + (z * z);
  1794. };
  1795. /**
  1796. * Returns a new Vector3 located at the center between "value1" and "value2".
  1797. */
  1798. Vector3.Center = function (value1, value2) {
  1799. var center = value1.add(value2);
  1800. center.scaleInPlace(0.5);
  1801. return center;
  1802. };
  1803. /**
  1804. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1805. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1806. * to something in order to rotate it from its local system to the given target system.
  1807. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1808. * Returns a new Vector3.
  1809. */
  1810. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1811. var rotation = Vector3.Zero();
  1812. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1813. return rotation;
  1814. };
  1815. /**
  1816. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1817. */
  1818. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1819. var quat = MathTmp.Quaternion[0];
  1820. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1821. quat.toEulerAnglesToRef(ref);
  1822. };
  1823. return Vector3;
  1824. }());
  1825. BABYLON.Vector3 = Vector3;
  1826. //Vector4 class created for EulerAngle class conversion to Quaternion
  1827. var Vector4 = /** @class */ (function () {
  1828. /**
  1829. * Creates a Vector4 object from the passed floats.
  1830. */
  1831. function Vector4(x, y, z, w) {
  1832. this.x = x;
  1833. this.y = y;
  1834. this.z = z;
  1835. this.w = w;
  1836. }
  1837. /**
  1838. * Returns the string with the Vector4 coordinates.
  1839. */
  1840. Vector4.prototype.toString = function () {
  1841. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1842. };
  1843. /**
  1844. * Returns the string "Vector4".
  1845. */
  1846. Vector4.prototype.getClassName = function () {
  1847. return "Vector4";
  1848. };
  1849. /**
  1850. * Returns the Vector4 hash code.
  1851. */
  1852. Vector4.prototype.getHashCode = function () {
  1853. var hash = this.x || 0;
  1854. hash = (hash * 397) ^ (this.y || 0);
  1855. hash = (hash * 397) ^ (this.z || 0);
  1856. hash = (hash * 397) ^ (this.w || 0);
  1857. return hash;
  1858. };
  1859. // Operators
  1860. /**
  1861. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1862. */
  1863. Vector4.prototype.asArray = function () {
  1864. var result = new Array();
  1865. this.toArray(result, 0);
  1866. return result;
  1867. };
  1868. /**
  1869. * Populates the passed array from the passed index with the Vector4 coordinates.
  1870. * Returns the Vector4.
  1871. */
  1872. Vector4.prototype.toArray = function (array, index) {
  1873. if (index === undefined) {
  1874. index = 0;
  1875. }
  1876. array[index] = this.x;
  1877. array[index + 1] = this.y;
  1878. array[index + 2] = this.z;
  1879. array[index + 3] = this.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Adds the passed vector to the current Vector4.
  1884. * Returns the updated Vector4.
  1885. */
  1886. Vector4.prototype.addInPlace = function (otherVector) {
  1887. this.x += otherVector.x;
  1888. this.y += otherVector.y;
  1889. this.z += otherVector.z;
  1890. this.w += otherVector.w;
  1891. return this;
  1892. };
  1893. /**
  1894. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1895. */
  1896. Vector4.prototype.add = function (otherVector) {
  1897. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1898. };
  1899. /**
  1900. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1901. * Returns the current Vector4.
  1902. */
  1903. Vector4.prototype.addToRef = function (otherVector, result) {
  1904. result.x = this.x + otherVector.x;
  1905. result.y = this.y + otherVector.y;
  1906. result.z = this.z + otherVector.z;
  1907. result.w = this.w + otherVector.w;
  1908. return this;
  1909. };
  1910. /**
  1911. * Subtract in place the passed vector from the current Vector4.
  1912. * Returns the updated Vector4.
  1913. */
  1914. Vector4.prototype.subtractInPlace = function (otherVector) {
  1915. this.x -= otherVector.x;
  1916. this.y -= otherVector.y;
  1917. this.z -= otherVector.z;
  1918. this.w -= otherVector.w;
  1919. return this;
  1920. };
  1921. /**
  1922. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1923. */
  1924. Vector4.prototype.subtract = function (otherVector) {
  1925. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1926. };
  1927. /**
  1928. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1929. * Returns the current Vector4.
  1930. */
  1931. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1932. result.x = this.x - otherVector.x;
  1933. result.y = this.y - otherVector.y;
  1934. result.z = this.z - otherVector.z;
  1935. result.w = this.w - otherVector.w;
  1936. return this;
  1937. };
  1938. /**
  1939. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1940. */
  1941. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1942. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1943. };
  1944. /**
  1945. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1946. * Returns the current Vector4.
  1947. */
  1948. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1949. result.x = this.x - x;
  1950. result.y = this.y - y;
  1951. result.z = this.z - z;
  1952. result.w = this.w - w;
  1953. return this;
  1954. };
  1955. /**
  1956. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1957. */
  1958. Vector4.prototype.negate = function () {
  1959. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1960. };
  1961. /**
  1962. * Multiplies the current Vector4 coordinates by scale (float).
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.scaleInPlace = function (scale) {
  1966. this.x *= scale;
  1967. this.y *= scale;
  1968. this.z *= scale;
  1969. this.w *= scale;
  1970. return this;
  1971. };
  1972. /**
  1973. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1974. */
  1975. Vector4.prototype.scale = function (scale) {
  1976. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1977. };
  1978. /**
  1979. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1980. * Returns the current Vector4.
  1981. */
  1982. Vector4.prototype.scaleToRef = function (scale, result) {
  1983. result.x = this.x * scale;
  1984. result.y = this.y * scale;
  1985. result.z = this.z * scale;
  1986. result.w = this.w * scale;
  1987. return this;
  1988. };
  1989. /**
  1990. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1991. */
  1992. Vector4.prototype.equals = function (otherVector) {
  1993. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1994. };
  1995. /**
  1996. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1997. */
  1998. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1999. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2000. return otherVector
  2001. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2002. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2003. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2004. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2005. };
  2006. /**
  2007. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2008. */
  2009. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2010. return this.x === x && this.y === y && this.z === z && this.w === w;
  2011. };
  2012. /**
  2013. * Multiplies in place the current Vector4 by the passed one.
  2014. * Returns the updated Vector4.
  2015. */
  2016. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2017. this.x *= otherVector.x;
  2018. this.y *= otherVector.y;
  2019. this.z *= otherVector.z;
  2020. this.w *= otherVector.w;
  2021. return this;
  2022. };
  2023. /**
  2024. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2025. */
  2026. Vector4.prototype.multiply = function (otherVector) {
  2027. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2028. };
  2029. /**
  2030. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2031. * Returns the current Vector4.
  2032. */
  2033. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2034. result.x = this.x * otherVector.x;
  2035. result.y = this.y * otherVector.y;
  2036. result.z = this.z * otherVector.z;
  2037. result.w = this.w * otherVector.w;
  2038. return this;
  2039. };
  2040. /**
  2041. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2042. */
  2043. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2044. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2045. };
  2046. /**
  2047. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2048. */
  2049. Vector4.prototype.divide = function (otherVector) {
  2050. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2051. };
  2052. /**
  2053. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2054. * Returns the current Vector4.
  2055. */
  2056. Vector4.prototype.divideToRef = function (otherVector, result) {
  2057. result.x = this.x / otherVector.x;
  2058. result.y = this.y / otherVector.y;
  2059. result.z = this.z / otherVector.z;
  2060. result.w = this.w / otherVector.w;
  2061. return this;
  2062. };
  2063. /**
  2064. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2065. */
  2066. Vector4.prototype.MinimizeInPlace = function (other) {
  2067. if (other.x < this.x)
  2068. this.x = other.x;
  2069. if (other.y < this.y)
  2070. this.y = other.y;
  2071. if (other.z < this.z)
  2072. this.z = other.z;
  2073. if (other.w < this.w)
  2074. this.w = other.w;
  2075. return this;
  2076. };
  2077. /**
  2078. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2079. */
  2080. Vector4.prototype.MaximizeInPlace = function (other) {
  2081. if (other.x > this.x)
  2082. this.x = other.x;
  2083. if (other.y > this.y)
  2084. this.y = other.y;
  2085. if (other.z > this.z)
  2086. this.z = other.z;
  2087. if (other.w > this.w)
  2088. this.w = other.w;
  2089. return this;
  2090. };
  2091. // Properties
  2092. /**
  2093. * Returns the Vector4 length (float).
  2094. */
  2095. Vector4.prototype.length = function () {
  2096. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2097. };
  2098. /**
  2099. * Returns the Vector4 squared length (float).
  2100. */
  2101. Vector4.prototype.lengthSquared = function () {
  2102. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2103. };
  2104. // Methods
  2105. /**
  2106. * Normalizes in place the Vector4.
  2107. * Returns the updated Vector4.
  2108. */
  2109. Vector4.prototype.normalize = function () {
  2110. var len = this.length();
  2111. if (len === 0)
  2112. return this;
  2113. var num = 1.0 / len;
  2114. this.x *= num;
  2115. this.y *= num;
  2116. this.z *= num;
  2117. this.w *= num;
  2118. return this;
  2119. };
  2120. /**
  2121. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2122. */
  2123. Vector4.prototype.toVector3 = function () {
  2124. return new Vector3(this.x, this.y, this.z);
  2125. };
  2126. /**
  2127. * Returns a new Vector4 copied from the current one.
  2128. */
  2129. Vector4.prototype.clone = function () {
  2130. return new Vector4(this.x, this.y, this.z, this.w);
  2131. };
  2132. /**
  2133. * Updates the current Vector4 with the passed one coordinates.
  2134. * Returns the updated Vector4.
  2135. */
  2136. Vector4.prototype.copyFrom = function (source) {
  2137. this.x = source.x;
  2138. this.y = source.y;
  2139. this.z = source.z;
  2140. this.w = source.w;
  2141. return this;
  2142. };
  2143. /**
  2144. * Updates the current Vector4 coordinates with the passed floats.
  2145. * Returns the updated Vector4.
  2146. */
  2147. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2148. this.x = x;
  2149. this.y = y;
  2150. this.z = z;
  2151. this.w = w;
  2152. return this;
  2153. };
  2154. /**
  2155. * Updates the current Vector4 coordinates with the passed floats.
  2156. * Returns the updated Vector4.
  2157. */
  2158. Vector4.prototype.set = function (x, y, z, w) {
  2159. return this.copyFromFloats(x, y, z, w);
  2160. };
  2161. // Statics
  2162. /**
  2163. * Returns a new Vector4 set from the starting index of the passed array.
  2164. */
  2165. Vector4.FromArray = function (array, offset) {
  2166. if (!offset) {
  2167. offset = 0;
  2168. }
  2169. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2170. };
  2171. /**
  2172. * Updates the passed vector "result" from the starting index of the passed array.
  2173. */
  2174. Vector4.FromArrayToRef = function (array, offset, result) {
  2175. result.x = array[offset];
  2176. result.y = array[offset + 1];
  2177. result.z = array[offset + 2];
  2178. result.w = array[offset + 3];
  2179. };
  2180. /**
  2181. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2182. */
  2183. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2184. Vector4.FromArrayToRef(array, offset, result);
  2185. };
  2186. /**
  2187. * Updates the passed vector "result" coordinates from the passed floats.
  2188. */
  2189. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2190. result.x = x;
  2191. result.y = y;
  2192. result.z = z;
  2193. result.w = w;
  2194. };
  2195. /**
  2196. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2197. */
  2198. Vector4.Zero = function () {
  2199. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2200. };
  2201. /**
  2202. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2203. */
  2204. Vector4.One = function () {
  2205. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2206. };
  2207. /**
  2208. * Returns a new normalized Vector4 from the passed one.
  2209. */
  2210. Vector4.Normalize = function (vector) {
  2211. var result = Vector4.Zero();
  2212. Vector4.NormalizeToRef(vector, result);
  2213. return result;
  2214. };
  2215. /**
  2216. * Updates the passed vector "result" from the normalization of the passed one.
  2217. */
  2218. Vector4.NormalizeToRef = function (vector, result) {
  2219. result.copyFrom(vector);
  2220. result.normalize();
  2221. };
  2222. Vector4.Minimize = function (left, right) {
  2223. var min = left.clone();
  2224. min.MinimizeInPlace(right);
  2225. return min;
  2226. };
  2227. Vector4.Maximize = function (left, right) {
  2228. var max = left.clone();
  2229. max.MaximizeInPlace(right);
  2230. return max;
  2231. };
  2232. /**
  2233. * Returns the distance (float) between the vectors "value1" and "value2".
  2234. */
  2235. Vector4.Distance = function (value1, value2) {
  2236. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2237. };
  2238. /**
  2239. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2240. */
  2241. Vector4.DistanceSquared = function (value1, value2) {
  2242. var x = value1.x - value2.x;
  2243. var y = value1.y - value2.y;
  2244. var z = value1.z - value2.z;
  2245. var w = value1.w - value2.w;
  2246. return (x * x) + (y * y) + (z * z) + (w * w);
  2247. };
  2248. /**
  2249. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2250. */
  2251. Vector4.Center = function (value1, value2) {
  2252. var center = value1.add(value2);
  2253. center.scaleInPlace(0.5);
  2254. return center;
  2255. };
  2256. /**
  2257. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2258. * This methods computes transformed normalized direction vectors only.
  2259. */
  2260. Vector4.TransformNormal = function (vector, transformation) {
  2261. var result = Vector4.Zero();
  2262. Vector4.TransformNormalToRef(vector, transformation, result);
  2263. return result;
  2264. };
  2265. /**
  2266. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2267. * This methods computes transformed normalized direction vectors only.
  2268. */
  2269. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2270. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2271. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2272. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2273. result.x = x;
  2274. result.y = y;
  2275. result.z = z;
  2276. result.w = vector.w;
  2277. };
  2278. /**
  2279. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2280. * This methods computes transformed normalized direction vectors only.
  2281. */
  2282. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2283. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2284. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2285. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2286. result.w = w;
  2287. };
  2288. return Vector4;
  2289. }());
  2290. BABYLON.Vector4 = Vector4;
  2291. var Size = /** @class */ (function () {
  2292. /**
  2293. * Creates a Size object from the passed width and height (floats).
  2294. */
  2295. function Size(width, height) {
  2296. this.width = width;
  2297. this.height = height;
  2298. }
  2299. // Returns a string with the Size width and height.
  2300. Size.prototype.toString = function () {
  2301. return "{W: " + this.width + ", H: " + this.height + "}";
  2302. };
  2303. /**
  2304. * Returns the string "Size"
  2305. */
  2306. Size.prototype.getClassName = function () {
  2307. return "Size";
  2308. };
  2309. /**
  2310. * Returns the Size hash code.
  2311. */
  2312. Size.prototype.getHashCode = function () {
  2313. var hash = this.width || 0;
  2314. hash = (hash * 397) ^ (this.height || 0);
  2315. return hash;
  2316. };
  2317. /**
  2318. * Updates the current size from the passed one.
  2319. * Returns the updated Size.
  2320. */
  2321. Size.prototype.copyFrom = function (src) {
  2322. this.width = src.width;
  2323. this.height = src.height;
  2324. };
  2325. /**
  2326. * Updates in place the current Size from the passed floats.
  2327. * Returns the updated Size.
  2328. */
  2329. Size.prototype.copyFromFloats = function (width, height) {
  2330. this.width = width;
  2331. this.height = height;
  2332. return this;
  2333. };
  2334. /**
  2335. * Updates in place the current Size from the passed floats.
  2336. * Returns the updated Size.
  2337. */
  2338. Size.prototype.set = function (width, height) {
  2339. return this.copyFromFloats(width, height);
  2340. };
  2341. /**
  2342. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2343. */
  2344. Size.prototype.multiplyByFloats = function (w, h) {
  2345. return new Size(this.width * w, this.height * h);
  2346. };
  2347. /**
  2348. * Returns a new Size copied from the passed one.
  2349. */
  2350. Size.prototype.clone = function () {
  2351. return new Size(this.width, this.height);
  2352. };
  2353. /**
  2354. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2355. */
  2356. Size.prototype.equals = function (other) {
  2357. if (!other) {
  2358. return false;
  2359. }
  2360. return (this.width === other.width) && (this.height === other.height);
  2361. };
  2362. Object.defineProperty(Size.prototype, "surface", {
  2363. /**
  2364. * Returns the surface of the Size : width * height (float).
  2365. */
  2366. get: function () {
  2367. return this.width * this.height;
  2368. },
  2369. enumerable: true,
  2370. configurable: true
  2371. });
  2372. /**
  2373. * Returns a new Size set to (0.0, 0.0)
  2374. */
  2375. Size.Zero = function () {
  2376. return new Size(0.0, 0.0);
  2377. };
  2378. /**
  2379. * Returns a new Size set as the addition result of the current Size and the passed one.
  2380. */
  2381. Size.prototype.add = function (otherSize) {
  2382. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2383. return r;
  2384. };
  2385. /**
  2386. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2387. */
  2388. Size.prototype.subtract = function (otherSize) {
  2389. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2390. return r;
  2391. };
  2392. /**
  2393. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2394. */
  2395. Size.Lerp = function (start, end, amount) {
  2396. var w = start.width + ((end.width - start.width) * amount);
  2397. var h = start.height + ((end.height - start.height) * amount);
  2398. return new Size(w, h);
  2399. };
  2400. return Size;
  2401. }());
  2402. BABYLON.Size = Size;
  2403. var Quaternion = /** @class */ (function () {
  2404. /**
  2405. * Creates a new Quaternion from the passed floats.
  2406. */
  2407. function Quaternion(x, y, z, w) {
  2408. if (x === void 0) { x = 0.0; }
  2409. if (y === void 0) { y = 0.0; }
  2410. if (z === void 0) { z = 0.0; }
  2411. if (w === void 0) { w = 1.0; }
  2412. this.x = x;
  2413. this.y = y;
  2414. this.z = z;
  2415. this.w = w;
  2416. }
  2417. /**
  2418. * Returns a string with the Quaternion coordinates.
  2419. */
  2420. Quaternion.prototype.toString = function () {
  2421. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2422. };
  2423. /**
  2424. * Returns the string "Quaternion".
  2425. */
  2426. Quaternion.prototype.getClassName = function () {
  2427. return "Quaternion";
  2428. };
  2429. /**
  2430. * Returns the Quaternion hash code.
  2431. */
  2432. Quaternion.prototype.getHashCode = function () {
  2433. var hash = this.x || 0;
  2434. hash = (hash * 397) ^ (this.y || 0);
  2435. hash = (hash * 397) ^ (this.z || 0);
  2436. hash = (hash * 397) ^ (this.w || 0);
  2437. return hash;
  2438. };
  2439. /**
  2440. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2441. */
  2442. Quaternion.prototype.asArray = function () {
  2443. return [this.x, this.y, this.z, this.w];
  2444. };
  2445. /**
  2446. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2447. */
  2448. Quaternion.prototype.equals = function (otherQuaternion) {
  2449. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2450. };
  2451. /**
  2452. * Returns a new Quaternion copied from the current one.
  2453. */
  2454. Quaternion.prototype.clone = function () {
  2455. return new Quaternion(this.x, this.y, this.z, this.w);
  2456. };
  2457. /**
  2458. * Updates the current Quaternion from the passed one coordinates.
  2459. * Returns the updated Quaterion.
  2460. */
  2461. Quaternion.prototype.copyFrom = function (other) {
  2462. this.x = other.x;
  2463. this.y = other.y;
  2464. this.z = other.z;
  2465. this.w = other.w;
  2466. return this;
  2467. };
  2468. /**
  2469. * Updates the current Quaternion from the passed float coordinates.
  2470. * Returns the updated Quaterion.
  2471. */
  2472. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2473. this.x = x;
  2474. this.y = y;
  2475. this.z = z;
  2476. this.w = w;
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed float coordinates.
  2481. * Returns the updated Quaterion.
  2482. */
  2483. Quaternion.prototype.set = function (x, y, z, w) {
  2484. return this.copyFromFloats(x, y, z, w);
  2485. };
  2486. /**
  2487. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2488. */
  2489. Quaternion.prototype.add = function (other) {
  2490. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2491. };
  2492. /**
  2493. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2494. */
  2495. Quaternion.prototype.subtract = function (other) {
  2496. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2497. };
  2498. /**
  2499. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2500. */
  2501. Quaternion.prototype.scale = function (value) {
  2502. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2503. };
  2504. /**
  2505. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2506. */
  2507. Quaternion.prototype.multiply = function (q1) {
  2508. var result = new Quaternion(0, 0, 0, 1.0);
  2509. this.multiplyToRef(q1, result);
  2510. return result;
  2511. };
  2512. /**
  2513. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2517. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2518. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2519. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2520. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2521. result.copyFromFloats(x, y, z, w);
  2522. return this;
  2523. };
  2524. /**
  2525. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2526. * Returns the updated Quaternion.
  2527. */
  2528. Quaternion.prototype.multiplyInPlace = function (q1) {
  2529. this.multiplyToRef(q1, this);
  2530. return this;
  2531. };
  2532. /**
  2533. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2534. * Returns the current Quaternion.
  2535. */
  2536. Quaternion.prototype.conjugateToRef = function (ref) {
  2537. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2538. return this;
  2539. };
  2540. /**
  2541. * Conjugates in place the current Quaternion.
  2542. * Returns the updated Quaternion.
  2543. */
  2544. Quaternion.prototype.conjugateInPlace = function () {
  2545. this.x *= -1;
  2546. this.y *= -1;
  2547. this.z *= -1;
  2548. return this;
  2549. };
  2550. /**
  2551. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2552. */
  2553. Quaternion.prototype.conjugate = function () {
  2554. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2555. return result;
  2556. };
  2557. /**
  2558. * Returns the Quaternion length (float).
  2559. */
  2560. Quaternion.prototype.length = function () {
  2561. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2562. };
  2563. /**
  2564. * Normalize in place the current Quaternion.
  2565. * Returns the updated Quaternion.
  2566. */
  2567. Quaternion.prototype.normalize = function () {
  2568. var length = 1.0 / this.length();
  2569. this.x *= length;
  2570. this.y *= length;
  2571. this.z *= length;
  2572. this.w *= length;
  2573. return this;
  2574. };
  2575. /**
  2576. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2577. */
  2578. Quaternion.prototype.toEulerAngles = function (order) {
  2579. if (order === void 0) { order = "YZX"; }
  2580. var result = Vector3.Zero();
  2581. this.toEulerAnglesToRef(result, order);
  2582. return result;
  2583. };
  2584. /**
  2585. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2586. * Returns the current Quaternion.
  2587. */
  2588. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2589. if (order === void 0) { order = "YZX"; }
  2590. var qz = this.z;
  2591. var qx = this.x;
  2592. var qy = this.y;
  2593. var qw = this.w;
  2594. var sqw = qw * qw;
  2595. var sqz = qz * qz;
  2596. var sqx = qx * qx;
  2597. var sqy = qy * qy;
  2598. var zAxisY = qy * qz - qx * qw;
  2599. var limit = .4999999;
  2600. if (zAxisY < -limit) {
  2601. result.y = 2 * Math.atan2(qy, qw);
  2602. result.x = Math.PI / 2;
  2603. result.z = 0;
  2604. }
  2605. else if (zAxisY > limit) {
  2606. result.y = 2 * Math.atan2(qy, qw);
  2607. result.x = -Math.PI / 2;
  2608. result.z = 0;
  2609. }
  2610. else {
  2611. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2612. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2613. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2614. }
  2615. return this;
  2616. };
  2617. /**
  2618. * Updates the passed rotation matrix with the current Quaternion values.
  2619. * Returns the current Quaternion.
  2620. */
  2621. Quaternion.prototype.toRotationMatrix = function (result) {
  2622. var xx = this.x * this.x;
  2623. var yy = this.y * this.y;
  2624. var zz = this.z * this.z;
  2625. var xy = this.x * this.y;
  2626. var zw = this.z * this.w;
  2627. var zx = this.z * this.x;
  2628. var yw = this.y * this.w;
  2629. var yz = this.y * this.z;
  2630. var xw = this.x * this.w;
  2631. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2632. result.m[1] = 2.0 * (xy + zw);
  2633. result.m[2] = 2.0 * (zx - yw);
  2634. result.m[3] = 0;
  2635. result.m[4] = 2.0 * (xy - zw);
  2636. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2637. result.m[6] = 2.0 * (yz + xw);
  2638. result.m[7] = 0;
  2639. result.m[8] = 2.0 * (zx + yw);
  2640. result.m[9] = 2.0 * (yz - xw);
  2641. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2642. result.m[11] = 0;
  2643. result.m[12] = 0;
  2644. result.m[13] = 0;
  2645. result.m[14] = 0;
  2646. result.m[15] = 1.0;
  2647. result._markAsUpdated();
  2648. return this;
  2649. };
  2650. /**
  2651. * Updates the current Quaternion from the passed rotation matrix values.
  2652. * Returns the updated Quaternion.
  2653. */
  2654. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2655. Quaternion.FromRotationMatrixToRef(matrix, this);
  2656. return this;
  2657. };
  2658. // Statics
  2659. /**
  2660. * Returns a new Quaternion set from the passed rotation matrix values.
  2661. */
  2662. Quaternion.FromRotationMatrix = function (matrix) {
  2663. var result = new Quaternion();
  2664. Quaternion.FromRotationMatrixToRef(matrix, result);
  2665. return result;
  2666. };
  2667. /**
  2668. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2669. */
  2670. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2671. var data = matrix.m;
  2672. var m11 = data[0], m12 = data[4], m13 = data[8];
  2673. var m21 = data[1], m22 = data[5], m23 = data[9];
  2674. var m31 = data[2], m32 = data[6], m33 = data[10];
  2675. var trace = m11 + m22 + m33;
  2676. var s;
  2677. if (trace > 0) {
  2678. s = 0.5 / Math.sqrt(trace + 1.0);
  2679. result.w = 0.25 / s;
  2680. result.x = (m32 - m23) * s;
  2681. result.y = (m13 - m31) * s;
  2682. result.z = (m21 - m12) * s;
  2683. }
  2684. else if (m11 > m22 && m11 > m33) {
  2685. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2686. result.w = (m32 - m23) / s;
  2687. result.x = 0.25 * s;
  2688. result.y = (m12 + m21) / s;
  2689. result.z = (m13 + m31) / s;
  2690. }
  2691. else if (m22 > m33) {
  2692. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2693. result.w = (m13 - m31) / s;
  2694. result.x = (m12 + m21) / s;
  2695. result.y = 0.25 * s;
  2696. result.z = (m23 + m32) / s;
  2697. }
  2698. else {
  2699. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2700. result.w = (m21 - m12) / s;
  2701. result.x = (m13 + m31) / s;
  2702. result.y = (m23 + m32) / s;
  2703. result.z = 0.25 * s;
  2704. }
  2705. };
  2706. /**
  2707. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2708. */
  2709. Quaternion.Zero = function () {
  2710. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2711. };
  2712. /**
  2713. * Returns a new Quaternion as the inverted current Quaternion.
  2714. */
  2715. Quaternion.Inverse = function (q) {
  2716. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2717. };
  2718. /**
  2719. * Returns the identity Quaternion.
  2720. */
  2721. Quaternion.Identity = function () {
  2722. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2723. };
  2724. Quaternion.IsIdentity = function (quaternion) {
  2725. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2726. };
  2727. /**
  2728. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2729. */
  2730. Quaternion.RotationAxis = function (axis, angle) {
  2731. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2732. };
  2733. /**
  2734. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2735. */
  2736. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2737. var sin = Math.sin(angle / 2);
  2738. axis.normalize();
  2739. result.w = Math.cos(angle / 2);
  2740. result.x = axis.x * sin;
  2741. result.y = axis.y * sin;
  2742. result.z = axis.z * sin;
  2743. return result;
  2744. };
  2745. /**
  2746. * Retuns a new Quaternion set from the starting index of the passed array.
  2747. */
  2748. Quaternion.FromArray = function (array, offset) {
  2749. if (!offset) {
  2750. offset = 0;
  2751. }
  2752. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2753. };
  2754. /**
  2755. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2756. */
  2757. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2758. var q = new Quaternion();
  2759. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2760. return q;
  2761. };
  2762. /**
  2763. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2764. */
  2765. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2766. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2767. var halfRoll = roll * 0.5;
  2768. var halfPitch = pitch * 0.5;
  2769. var halfYaw = yaw * 0.5;
  2770. var sinRoll = Math.sin(halfRoll);
  2771. var cosRoll = Math.cos(halfRoll);
  2772. var sinPitch = Math.sin(halfPitch);
  2773. var cosPitch = Math.cos(halfPitch);
  2774. var sinYaw = Math.sin(halfYaw);
  2775. var cosYaw = Math.cos(halfYaw);
  2776. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2777. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2778. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2779. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2780. };
  2781. /**
  2782. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2783. */
  2784. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2785. var result = new Quaternion();
  2786. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2787. return result;
  2788. };
  2789. /**
  2790. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2791. */
  2792. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2793. // Produces a quaternion from Euler angles in the z-x-z orientation
  2794. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2795. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2796. var halfBeta = beta * 0.5;
  2797. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2798. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2799. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2800. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2801. };
  2802. /**
  2803. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2804. * cf to Vector3.RotationFromAxis() documentation.
  2805. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2806. */
  2807. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2808. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2809. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2810. return quat;
  2811. };
  2812. /**
  2813. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2814. * cf to Vector3.RotationFromAxis() documentation.
  2815. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2816. */
  2817. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2818. var rotMat = MathTmp.Matrix[0];
  2819. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2820. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2821. };
  2822. Quaternion.Slerp = function (left, right, amount) {
  2823. var result = Quaternion.Identity();
  2824. Quaternion.SlerpToRef(left, right, amount, result);
  2825. return result;
  2826. };
  2827. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2828. var num2;
  2829. var num3;
  2830. var num = amount;
  2831. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2832. var flag = false;
  2833. if (num4 < 0) {
  2834. flag = true;
  2835. num4 = -num4;
  2836. }
  2837. if (num4 > 0.999999) {
  2838. num3 = 1 - num;
  2839. num2 = flag ? -num : num;
  2840. }
  2841. else {
  2842. var num5 = Math.acos(num4);
  2843. var num6 = (1.0 / Math.sin(num5));
  2844. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2845. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2846. }
  2847. result.x = (num3 * left.x) + (num2 * right.x);
  2848. result.y = (num3 * left.y) + (num2 * right.y);
  2849. result.z = (num3 * left.z) + (num2 * right.z);
  2850. result.w = (num3 * left.w) + (num2 * right.w);
  2851. };
  2852. /**
  2853. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2854. */
  2855. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2856. var squared = amount * amount;
  2857. var cubed = amount * squared;
  2858. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2859. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2860. var part3 = (cubed - (2.0 * squared)) + amount;
  2861. var part4 = cubed - squared;
  2862. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2863. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2864. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2865. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2866. return new Quaternion(x, y, z, w);
  2867. };
  2868. return Quaternion;
  2869. }());
  2870. BABYLON.Quaternion = Quaternion;
  2871. var Matrix = /** @class */ (function () {
  2872. function Matrix() {
  2873. this._isIdentity = false;
  2874. this._isIdentityDirty = true;
  2875. this.m = new Float32Array(16);
  2876. this._markAsUpdated();
  2877. }
  2878. Matrix.prototype._markAsUpdated = function () {
  2879. this.updateFlag = Matrix._updateFlagSeed++;
  2880. this._isIdentityDirty = true;
  2881. };
  2882. // Properties
  2883. /**
  2884. * Boolean : True is the matrix is the identity matrix
  2885. */
  2886. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2887. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2888. if (this._isIdentityDirty) {
  2889. this._isIdentityDirty = false;
  2890. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2891. this._isIdentity = false;
  2892. }
  2893. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2894. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2895. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2896. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2897. this._isIdentity = false;
  2898. }
  2899. else {
  2900. this._isIdentity = true;
  2901. }
  2902. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2903. this._isIdentity = false;
  2904. }
  2905. }
  2906. return this._isIdentity;
  2907. };
  2908. /**
  2909. * Returns the matrix determinant (float).
  2910. */
  2911. Matrix.prototype.determinant = function () {
  2912. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2913. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2914. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2915. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2916. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2917. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2918. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2919. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2920. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2921. };
  2922. // Methods
  2923. /**
  2924. * Returns the matrix underlying array.
  2925. */
  2926. Matrix.prototype.toArray = function () {
  2927. return this.m;
  2928. };
  2929. /**
  2930. * Returns the matrix underlying array.
  2931. */
  2932. Matrix.prototype.asArray = function () {
  2933. return this.toArray();
  2934. };
  2935. /**
  2936. * Inverts in place the Matrix.
  2937. * Returns the Matrix inverted.
  2938. */
  2939. Matrix.prototype.invert = function () {
  2940. this.invertToRef(this);
  2941. return this;
  2942. };
  2943. /**
  2944. * Sets all the matrix elements to zero.
  2945. * Returns the Matrix.
  2946. */
  2947. Matrix.prototype.reset = function () {
  2948. for (var index = 0; index < 16; index++) {
  2949. this.m[index] = 0.0;
  2950. }
  2951. this._markAsUpdated();
  2952. return this;
  2953. };
  2954. /**
  2955. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2956. */
  2957. Matrix.prototype.add = function (other) {
  2958. var result = new Matrix();
  2959. this.addToRef(other, result);
  2960. return result;
  2961. };
  2962. /**
  2963. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2964. * Returns the Matrix.
  2965. */
  2966. Matrix.prototype.addToRef = function (other, result) {
  2967. for (var index = 0; index < 16; index++) {
  2968. result.m[index] = this.m[index] + other.m[index];
  2969. }
  2970. result._markAsUpdated();
  2971. return this;
  2972. };
  2973. /**
  2974. * Adds in place the passed matrix to the current Matrix.
  2975. * Returns the updated Matrix.
  2976. */
  2977. Matrix.prototype.addToSelf = function (other) {
  2978. for (var index = 0; index < 16; index++) {
  2979. this.m[index] += other.m[index];
  2980. }
  2981. this._markAsUpdated();
  2982. return this;
  2983. };
  2984. /**
  2985. * Sets the passed matrix with the current inverted Matrix.
  2986. * Returns the unmodified current Matrix.
  2987. */
  2988. Matrix.prototype.invertToRef = function (other) {
  2989. var l1 = this.m[0];
  2990. var l2 = this.m[1];
  2991. var l3 = this.m[2];
  2992. var l4 = this.m[3];
  2993. var l5 = this.m[4];
  2994. var l6 = this.m[5];
  2995. var l7 = this.m[6];
  2996. var l8 = this.m[7];
  2997. var l9 = this.m[8];
  2998. var l10 = this.m[9];
  2999. var l11 = this.m[10];
  3000. var l12 = this.m[11];
  3001. var l13 = this.m[12];
  3002. var l14 = this.m[13];
  3003. var l15 = this.m[14];
  3004. var l16 = this.m[15];
  3005. var l17 = (l11 * l16) - (l12 * l15);
  3006. var l18 = (l10 * l16) - (l12 * l14);
  3007. var l19 = (l10 * l15) - (l11 * l14);
  3008. var l20 = (l9 * l16) - (l12 * l13);
  3009. var l21 = (l9 * l15) - (l11 * l13);
  3010. var l22 = (l9 * l14) - (l10 * l13);
  3011. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3012. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3013. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3014. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3015. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3016. var l28 = (l7 * l16) - (l8 * l15);
  3017. var l29 = (l6 * l16) - (l8 * l14);
  3018. var l30 = (l6 * l15) - (l7 * l14);
  3019. var l31 = (l5 * l16) - (l8 * l13);
  3020. var l32 = (l5 * l15) - (l7 * l13);
  3021. var l33 = (l5 * l14) - (l6 * l13);
  3022. var l34 = (l7 * l12) - (l8 * l11);
  3023. var l35 = (l6 * l12) - (l8 * l10);
  3024. var l36 = (l6 * l11) - (l7 * l10);
  3025. var l37 = (l5 * l12) - (l8 * l9);
  3026. var l38 = (l5 * l11) - (l7 * l9);
  3027. var l39 = (l5 * l10) - (l6 * l9);
  3028. other.m[0] = l23 * l27;
  3029. other.m[4] = l24 * l27;
  3030. other.m[8] = l25 * l27;
  3031. other.m[12] = l26 * l27;
  3032. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3033. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3034. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3035. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3036. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3037. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3038. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3039. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3040. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3041. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3042. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3043. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3044. other._markAsUpdated();
  3045. return this;
  3046. };
  3047. /**
  3048. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3049. * Returns the updated Matrix.
  3050. */
  3051. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3052. this.m[12] = x;
  3053. this.m[13] = y;
  3054. this.m[14] = z;
  3055. this._markAsUpdated();
  3056. return this;
  3057. };
  3058. /**
  3059. * Inserts the translation vector in the current Matrix.
  3060. * Returns the updated Matrix.
  3061. */
  3062. Matrix.prototype.setTranslation = function (vector3) {
  3063. this.m[12] = vector3.x;
  3064. this.m[13] = vector3.y;
  3065. this.m[14] = vector3.z;
  3066. this._markAsUpdated();
  3067. return this;
  3068. };
  3069. /**
  3070. * Returns a new Vector3 as the extracted translation from the Matrix.
  3071. */
  3072. Matrix.prototype.getTranslation = function () {
  3073. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3074. };
  3075. /**
  3076. * Fill a Vector3 with the extracted translation from the Matrix.
  3077. */
  3078. Matrix.prototype.getTranslationToRef = function (result) {
  3079. result.x = this.m[12];
  3080. result.y = this.m[13];
  3081. result.z = this.m[14];
  3082. return this;
  3083. };
  3084. /**
  3085. * Remove rotation and scaling part from the Matrix.
  3086. * Returns the updated Matrix.
  3087. */
  3088. Matrix.prototype.removeRotationAndScaling = function () {
  3089. this.setRowFromFloats(0, 1, 0, 0, 0);
  3090. this.setRowFromFloats(1, 0, 1, 0, 0);
  3091. this.setRowFromFloats(2, 0, 0, 1, 0);
  3092. return this;
  3093. };
  3094. /**
  3095. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3096. */
  3097. Matrix.prototype.multiply = function (other) {
  3098. var result = new Matrix();
  3099. this.multiplyToRef(other, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Updates the current Matrix from the passed one values.
  3104. * Returns the updated Matrix.
  3105. */
  3106. Matrix.prototype.copyFrom = function (other) {
  3107. for (var index = 0; index < 16; index++) {
  3108. this.m[index] = other.m[index];
  3109. }
  3110. this._markAsUpdated();
  3111. return this;
  3112. };
  3113. /**
  3114. * Populates the passed array from the starting index with the Matrix values.
  3115. * Returns the Matrix.
  3116. */
  3117. Matrix.prototype.copyToArray = function (array, offset) {
  3118. if (offset === void 0) { offset = 0; }
  3119. for (var index = 0; index < 16; index++) {
  3120. array[offset + index] = this.m[index];
  3121. }
  3122. return this;
  3123. };
  3124. /**
  3125. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3126. */
  3127. Matrix.prototype.multiplyToRef = function (other, result) {
  3128. this.multiplyToArray(other, result.m, 0);
  3129. result._markAsUpdated();
  3130. return this;
  3131. };
  3132. /**
  3133. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3134. */
  3135. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3136. var tm0 = this.m[0];
  3137. var tm1 = this.m[1];
  3138. var tm2 = this.m[2];
  3139. var tm3 = this.m[3];
  3140. var tm4 = this.m[4];
  3141. var tm5 = this.m[5];
  3142. var tm6 = this.m[6];
  3143. var tm7 = this.m[7];
  3144. var tm8 = this.m[8];
  3145. var tm9 = this.m[9];
  3146. var tm10 = this.m[10];
  3147. var tm11 = this.m[11];
  3148. var tm12 = this.m[12];
  3149. var tm13 = this.m[13];
  3150. var tm14 = this.m[14];
  3151. var tm15 = this.m[15];
  3152. var om0 = other.m[0];
  3153. var om1 = other.m[1];
  3154. var om2 = other.m[2];
  3155. var om3 = other.m[3];
  3156. var om4 = other.m[4];
  3157. var om5 = other.m[5];
  3158. var om6 = other.m[6];
  3159. var om7 = other.m[7];
  3160. var om8 = other.m[8];
  3161. var om9 = other.m[9];
  3162. var om10 = other.m[10];
  3163. var om11 = other.m[11];
  3164. var om12 = other.m[12];
  3165. var om13 = other.m[13];
  3166. var om14 = other.m[14];
  3167. var om15 = other.m[15];
  3168. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3169. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3170. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3171. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3172. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3173. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3174. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3175. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3176. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3177. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3178. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3179. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3180. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3181. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3182. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3183. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3184. return this;
  3185. };
  3186. /**
  3187. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3188. */
  3189. Matrix.prototype.equals = function (value) {
  3190. return value &&
  3191. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3192. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3193. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3194. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3195. };
  3196. /**
  3197. * Returns a new Matrix from the current Matrix.
  3198. */
  3199. Matrix.prototype.clone = function () {
  3200. 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]);
  3201. };
  3202. /**
  3203. * Returns the string "Matrix"
  3204. */
  3205. Matrix.prototype.getClassName = function () {
  3206. return "Matrix";
  3207. };
  3208. /**
  3209. * Returns the Matrix hash code.
  3210. */
  3211. Matrix.prototype.getHashCode = function () {
  3212. var hash = this.m[0] || 0;
  3213. for (var i = 1; i < 16; i++) {
  3214. hash = (hash * 397) ^ (this.m[i] || 0);
  3215. }
  3216. return hash;
  3217. };
  3218. /**
  3219. * Decomposes the current Matrix into :
  3220. * - a scale vector3 passed as a reference to update,
  3221. * - a rotation quaternion passed as a reference to update,
  3222. * - a translation vector3 passed as a reference to update.
  3223. * Returns the boolean `true`.
  3224. */
  3225. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3226. translation.x = this.m[12];
  3227. translation.y = this.m[13];
  3228. translation.z = this.m[14];
  3229. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3230. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3231. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3232. if (this.determinant() <= 0) {
  3233. scale.y *= -1;
  3234. }
  3235. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3236. rotation.x = 0;
  3237. rotation.y = 0;
  3238. rotation.z = 0;
  3239. rotation.w = 1;
  3240. return false;
  3241. }
  3242. 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]);
  3243. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3244. return true;
  3245. };
  3246. /**
  3247. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3248. */
  3249. Matrix.prototype.getRotationMatrix = function () {
  3250. var result = Matrix.Identity();
  3251. this.getRotationMatrixToRef(result);
  3252. return result;
  3253. };
  3254. /**
  3255. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3256. * Returns the current Matrix.
  3257. */
  3258. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3259. var m = this.m;
  3260. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3261. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3262. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3263. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3264. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3265. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3266. 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);
  3267. return this;
  3268. };
  3269. // Statics
  3270. /**
  3271. * Returns a new Matrix set from the starting index of the passed array.
  3272. */
  3273. Matrix.FromArray = function (array, offset) {
  3274. var result = new Matrix();
  3275. if (!offset) {
  3276. offset = 0;
  3277. }
  3278. Matrix.FromArrayToRef(array, offset, result);
  3279. return result;
  3280. };
  3281. /**
  3282. * Sets the passed "result" matrix from the starting index of the passed array.
  3283. */
  3284. Matrix.FromArrayToRef = function (array, offset, result) {
  3285. for (var index = 0; index < 16; index++) {
  3286. result.m[index] = array[index + offset];
  3287. }
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3292. */
  3293. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3294. for (var index = 0; index < 16; index++) {
  3295. result.m[index] = array[index + offset] * scale;
  3296. }
  3297. result._markAsUpdated();
  3298. };
  3299. /**
  3300. * Sets the passed matrix "result" with the 16 passed floats.
  3301. */
  3302. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3303. result.m[0] = initialM11;
  3304. result.m[1] = initialM12;
  3305. result.m[2] = initialM13;
  3306. result.m[3] = initialM14;
  3307. result.m[4] = initialM21;
  3308. result.m[5] = initialM22;
  3309. result.m[6] = initialM23;
  3310. result.m[7] = initialM24;
  3311. result.m[8] = initialM31;
  3312. result.m[9] = initialM32;
  3313. result.m[10] = initialM33;
  3314. result.m[11] = initialM34;
  3315. result.m[12] = initialM41;
  3316. result.m[13] = initialM42;
  3317. result.m[14] = initialM43;
  3318. result.m[15] = initialM44;
  3319. result._markAsUpdated();
  3320. };
  3321. /**
  3322. * Returns the index-th row of the current matrix as a new Vector4.
  3323. */
  3324. Matrix.prototype.getRow = function (index) {
  3325. if (index < 0 || index > 3) {
  3326. return null;
  3327. }
  3328. var i = index * 4;
  3329. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3330. };
  3331. /**
  3332. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3333. * Returns the updated Matrix.
  3334. */
  3335. Matrix.prototype.setRow = function (index, row) {
  3336. if (index < 0 || index > 3) {
  3337. return this;
  3338. }
  3339. var i = index * 4;
  3340. this.m[i + 0] = row.x;
  3341. this.m[i + 1] = row.y;
  3342. this.m[i + 2] = row.z;
  3343. this.m[i + 3] = row.w;
  3344. this._markAsUpdated();
  3345. return this;
  3346. };
  3347. /**
  3348. * Compute the transpose of the matrix.
  3349. * Returns a new Matrix.
  3350. */
  3351. Matrix.prototype.transpose = function () {
  3352. return Matrix.Transpose(this);
  3353. };
  3354. /**
  3355. * Compute the transpose of the matrix.
  3356. * Returns the current matrix.
  3357. */
  3358. Matrix.prototype.transposeToRef = function (result) {
  3359. Matrix.TransposeToRef(this, result);
  3360. return this;
  3361. };
  3362. /**
  3363. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3364. * Returns the updated Matrix.
  3365. */
  3366. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3367. if (index < 0 || index > 3) {
  3368. return this;
  3369. }
  3370. var i = index * 4;
  3371. this.m[i + 0] = x;
  3372. this.m[i + 1] = y;
  3373. this.m[i + 2] = z;
  3374. this.m[i + 3] = w;
  3375. this._markAsUpdated();
  3376. return this;
  3377. };
  3378. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3379. /**
  3380. * Static identity matrix to be used as readonly matrix
  3381. * Must not be updated.
  3382. */
  3383. get: function () {
  3384. return Matrix._identityReadOnly;
  3385. },
  3386. enumerable: true,
  3387. configurable: true
  3388. });
  3389. /**
  3390. * Returns a new Matrix set from the 16 passed floats.
  3391. */
  3392. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3393. var result = new Matrix();
  3394. result.m[0] = initialM11;
  3395. result.m[1] = initialM12;
  3396. result.m[2] = initialM13;
  3397. result.m[3] = initialM14;
  3398. result.m[4] = initialM21;
  3399. result.m[5] = initialM22;
  3400. result.m[6] = initialM23;
  3401. result.m[7] = initialM24;
  3402. result.m[8] = initialM31;
  3403. result.m[9] = initialM32;
  3404. result.m[10] = initialM33;
  3405. result.m[11] = initialM34;
  3406. result.m[12] = initialM41;
  3407. result.m[13] = initialM42;
  3408. result.m[14] = initialM43;
  3409. result.m[15] = initialM44;
  3410. return result;
  3411. };
  3412. /**
  3413. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3414. */
  3415. Matrix.Compose = function (scale, rotation, translation) {
  3416. var result = Matrix.Identity();
  3417. Matrix.ComposeToRef(scale, rotation, translation, result);
  3418. return result;
  3419. };
  3420. /**
  3421. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3422. */
  3423. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3424. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3425. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3426. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3427. result.setTranslation(translation);
  3428. };
  3429. /**
  3430. * Returns a new indentity Matrix.
  3431. */
  3432. Matrix.Identity = function () {
  3433. 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);
  3434. };
  3435. /**
  3436. * Sets the passed "result" as an identity matrix.
  3437. */
  3438. Matrix.IdentityToRef = function (result) {
  3439. 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);
  3440. };
  3441. /**
  3442. * Returns a new zero Matrix.
  3443. */
  3444. Matrix.Zero = function () {
  3445. 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);
  3446. };
  3447. /**
  3448. * Returns a new rotation matrix for "angle" radians around the X axis.
  3449. */
  3450. Matrix.RotationX = function (angle) {
  3451. var result = new Matrix();
  3452. Matrix.RotationXToRef(angle, result);
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix as the passed inverted one.
  3457. */
  3458. Matrix.Invert = function (source) {
  3459. var result = new Matrix();
  3460. source.invertToRef(result);
  3461. return result;
  3462. };
  3463. /**
  3464. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3465. */
  3466. Matrix.RotationXToRef = function (angle, result) {
  3467. var s = Math.sin(angle);
  3468. var c = Math.cos(angle);
  3469. result.m[0] = 1.0;
  3470. result.m[15] = 1.0;
  3471. result.m[5] = c;
  3472. result.m[10] = c;
  3473. result.m[9] = -s;
  3474. result.m[6] = s;
  3475. result.m[1] = 0.0;
  3476. result.m[2] = 0.0;
  3477. result.m[3] = 0.0;
  3478. result.m[4] = 0.0;
  3479. result.m[7] = 0.0;
  3480. result.m[8] = 0.0;
  3481. result.m[11] = 0.0;
  3482. result.m[12] = 0.0;
  3483. result.m[13] = 0.0;
  3484. result.m[14] = 0.0;
  3485. result._markAsUpdated();
  3486. };
  3487. /**
  3488. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3489. */
  3490. Matrix.RotationY = function (angle) {
  3491. var result = new Matrix();
  3492. Matrix.RotationYToRef(angle, result);
  3493. return result;
  3494. };
  3495. /**
  3496. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3497. */
  3498. Matrix.RotationYToRef = function (angle, result) {
  3499. var s = Math.sin(angle);
  3500. var c = Math.cos(angle);
  3501. result.m[5] = 1.0;
  3502. result.m[15] = 1.0;
  3503. result.m[0] = c;
  3504. result.m[2] = -s;
  3505. result.m[8] = s;
  3506. result.m[10] = c;
  3507. result.m[1] = 0.0;
  3508. result.m[3] = 0.0;
  3509. result.m[4] = 0.0;
  3510. result.m[6] = 0.0;
  3511. result.m[7] = 0.0;
  3512. result.m[9] = 0.0;
  3513. result.m[11] = 0.0;
  3514. result.m[12] = 0.0;
  3515. result.m[13] = 0.0;
  3516. result.m[14] = 0.0;
  3517. result._markAsUpdated();
  3518. };
  3519. /**
  3520. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3521. */
  3522. Matrix.RotationZ = function (angle) {
  3523. var result = new Matrix();
  3524. Matrix.RotationZToRef(angle, result);
  3525. return result;
  3526. };
  3527. /**
  3528. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3529. */
  3530. Matrix.RotationZToRef = function (angle, result) {
  3531. var s = Math.sin(angle);
  3532. var c = Math.cos(angle);
  3533. result.m[10] = 1.0;
  3534. result.m[15] = 1.0;
  3535. result.m[0] = c;
  3536. result.m[1] = s;
  3537. result.m[4] = -s;
  3538. result.m[5] = c;
  3539. result.m[2] = 0.0;
  3540. result.m[3] = 0.0;
  3541. result.m[6] = 0.0;
  3542. result.m[7] = 0.0;
  3543. result.m[8] = 0.0;
  3544. result.m[9] = 0.0;
  3545. result.m[11] = 0.0;
  3546. result.m[12] = 0.0;
  3547. result.m[13] = 0.0;
  3548. result.m[14] = 0.0;
  3549. result._markAsUpdated();
  3550. };
  3551. /**
  3552. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3553. */
  3554. Matrix.RotationAxis = function (axis, angle) {
  3555. var result = Matrix.Zero();
  3556. Matrix.RotationAxisToRef(axis, angle, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3561. */
  3562. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3563. var s = Math.sin(-angle);
  3564. var c = Math.cos(-angle);
  3565. var c1 = 1 - c;
  3566. axis.normalize();
  3567. result.m[0] = (axis.x * axis.x) * c1 + c;
  3568. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3569. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3570. result.m[3] = 0.0;
  3571. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3572. result.m[5] = (axis.y * axis.y) * c1 + c;
  3573. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3574. result.m[7] = 0.0;
  3575. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3576. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3577. result.m[10] = (axis.z * axis.z) * c1 + c;
  3578. result.m[11] = 0.0;
  3579. result.m[15] = 1.0;
  3580. result._markAsUpdated();
  3581. };
  3582. /**
  3583. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3584. */
  3585. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3586. var result = new Matrix();
  3587. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3588. return result;
  3589. };
  3590. /**
  3591. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3592. */
  3593. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3594. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3595. this._tempQuaternion.toRotationMatrix(result);
  3596. };
  3597. /**
  3598. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3599. */
  3600. Matrix.Scaling = function (x, y, z) {
  3601. var result = Matrix.Zero();
  3602. Matrix.ScalingToRef(x, y, z, result);
  3603. return result;
  3604. };
  3605. /**
  3606. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3607. */
  3608. Matrix.ScalingToRef = function (x, y, z, result) {
  3609. result.m[0] = x;
  3610. result.m[1] = 0.0;
  3611. result.m[2] = 0.0;
  3612. result.m[3] = 0.0;
  3613. result.m[4] = 0.0;
  3614. result.m[5] = y;
  3615. result.m[6] = 0.0;
  3616. result.m[7] = 0.0;
  3617. result.m[8] = 0.0;
  3618. result.m[9] = 0.0;
  3619. result.m[10] = z;
  3620. result.m[11] = 0.0;
  3621. result.m[12] = 0.0;
  3622. result.m[13] = 0.0;
  3623. result.m[14] = 0.0;
  3624. result.m[15] = 1.0;
  3625. result._markAsUpdated();
  3626. };
  3627. /**
  3628. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3629. */
  3630. Matrix.Translation = function (x, y, z) {
  3631. var result = Matrix.Identity();
  3632. Matrix.TranslationToRef(x, y, z, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3637. */
  3638. Matrix.TranslationToRef = function (x, y, z, result) {
  3639. 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);
  3640. };
  3641. /**
  3642. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3643. */
  3644. Matrix.Lerp = function (startValue, endValue, gradient) {
  3645. var result = Matrix.Zero();
  3646. for (var index = 0; index < 16; index++) {
  3647. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3648. }
  3649. result._markAsUpdated();
  3650. return result;
  3651. };
  3652. /**
  3653. * Returns a new Matrix whose values are computed by :
  3654. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3655. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3656. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3657. */
  3658. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3659. var startScale = new Vector3(0, 0, 0);
  3660. var startRotation = new Quaternion();
  3661. var startTranslation = new Vector3(0, 0, 0);
  3662. startValue.decompose(startScale, startRotation, startTranslation);
  3663. var endScale = new Vector3(0, 0, 0);
  3664. var endRotation = new Quaternion();
  3665. var endTranslation = new Vector3(0, 0, 0);
  3666. endValue.decompose(endScale, endRotation, endTranslation);
  3667. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3668. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3669. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3670. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3671. };
  3672. /**
  3673. * 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".
  3674. * This methods works for a Left-Handed system.
  3675. */
  3676. Matrix.LookAtLH = function (eye, target, up) {
  3677. var result = Matrix.Zero();
  3678. Matrix.LookAtLHToRef(eye, target, up, result);
  3679. return result;
  3680. };
  3681. /**
  3682. * 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".
  3683. * This methods works for a Left-Handed system.
  3684. */
  3685. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3686. // Z axis
  3687. target.subtractToRef(eye, this._zAxis);
  3688. this._zAxis.normalize();
  3689. // X axis
  3690. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3691. if (this._xAxis.lengthSquared() === 0) {
  3692. this._xAxis.x = 1.0;
  3693. }
  3694. else {
  3695. this._xAxis.normalize();
  3696. }
  3697. // Y axis
  3698. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3699. this._yAxis.normalize();
  3700. // Eye angles
  3701. var ex = -Vector3.Dot(this._xAxis, eye);
  3702. var ey = -Vector3.Dot(this._yAxis, eye);
  3703. var ez = -Vector3.Dot(this._zAxis, eye);
  3704. 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);
  3705. };
  3706. /**
  3707. * 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".
  3708. * This methods works for a Right-Handed system.
  3709. */
  3710. Matrix.LookAtRH = function (eye, target, up) {
  3711. var result = Matrix.Zero();
  3712. Matrix.LookAtRHToRef(eye, target, up, result);
  3713. return result;
  3714. };
  3715. /**
  3716. * 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".
  3717. * This methods works for a Left-Handed system.
  3718. */
  3719. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3720. // Z axis
  3721. eye.subtractToRef(target, this._zAxis);
  3722. this._zAxis.normalize();
  3723. // X axis
  3724. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3725. if (this._xAxis.lengthSquared() === 0) {
  3726. this._xAxis.x = 1.0;
  3727. }
  3728. else {
  3729. this._xAxis.normalize();
  3730. }
  3731. // Y axis
  3732. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3733. this._yAxis.normalize();
  3734. // Eye angles
  3735. var ex = -Vector3.Dot(this._xAxis, eye);
  3736. var ey = -Vector3.Dot(this._yAxis, eye);
  3737. var ez = -Vector3.Dot(this._zAxis, eye);
  3738. 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);
  3739. };
  3740. /**
  3741. * 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.
  3742. */
  3743. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3744. var matrix = Matrix.Zero();
  3745. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3746. return matrix;
  3747. };
  3748. /**
  3749. * 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.
  3750. */
  3751. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3752. var n = znear;
  3753. var f = zfar;
  3754. var a = 2.0 / width;
  3755. var b = 2.0 / height;
  3756. var c = 2.0 / (f - n);
  3757. var d = -(f + n) / (f - n);
  3758. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3759. };
  3760. /**
  3761. * 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.
  3762. */
  3763. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3764. var matrix = Matrix.Zero();
  3765. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3766. return matrix;
  3767. };
  3768. /**
  3769. * 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.
  3770. */
  3771. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3772. var n = znear;
  3773. var f = zfar;
  3774. var a = 2.0 / (right - left);
  3775. var b = 2.0 / (top - bottom);
  3776. var c = 2.0 / (f - n);
  3777. var d = -(f + n) / (f - n);
  3778. var i0 = (left + right) / (left - right);
  3779. var i1 = (top + bottom) / (bottom - top);
  3780. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3781. };
  3782. /**
  3783. * 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.
  3784. */
  3785. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3786. var matrix = Matrix.Zero();
  3787. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3788. return matrix;
  3789. };
  3790. /**
  3791. * 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.
  3792. */
  3793. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3794. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3795. result.m[10] *= -1.0;
  3796. };
  3797. /**
  3798. * 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.
  3799. */
  3800. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3801. var matrix = Matrix.Zero();
  3802. var n = znear;
  3803. var f = zfar;
  3804. var a = 2.0 * n / width;
  3805. var b = 2.0 * n / height;
  3806. var c = (f + n) / (f - n);
  3807. var d = -2.0 * f * n / (f - n);
  3808. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3809. return matrix;
  3810. };
  3811. /**
  3812. * 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.
  3813. */
  3814. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3815. var matrix = Matrix.Zero();
  3816. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3817. return matrix;
  3818. };
  3819. /**
  3820. * 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.
  3821. */
  3822. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3823. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3824. var n = znear;
  3825. var f = zfar;
  3826. var t = 1.0 / (Math.tan(fov * 0.5));
  3827. var a = isVerticalFovFixed ? (t / aspect) : t;
  3828. var b = isVerticalFovFixed ? t : (t * aspect);
  3829. var c = (f + n) / (f - n);
  3830. var d = -2.0 * f * n / (f - n);
  3831. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3832. };
  3833. /**
  3834. * 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.
  3835. */
  3836. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3837. var matrix = Matrix.Zero();
  3838. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3839. return matrix;
  3840. };
  3841. /**
  3842. * 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.
  3843. */
  3844. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3845. //alternatively this could be expressed as:
  3846. // m = PerspectiveFovLHToRef
  3847. // m[10] *= -1.0;
  3848. // m[11] *= -1.0;
  3849. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3850. var n = znear;
  3851. var f = zfar;
  3852. var t = 1.0 / (Math.tan(fov * 0.5));
  3853. var a = isVerticalFovFixed ? (t / aspect) : t;
  3854. var b = isVerticalFovFixed ? t : (t * aspect);
  3855. var c = -(f + n) / (f - n);
  3856. var d = -2 * f * n / (f - n);
  3857. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3858. };
  3859. /**
  3860. * 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.
  3861. */
  3862. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3863. if (rightHanded === void 0) { rightHanded = false; }
  3864. var rightHandedFactor = rightHanded ? -1 : 1;
  3865. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3866. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3867. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3868. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3869. var xScale = 2.0 / (leftTan + rightTan);
  3870. var yScale = 2.0 / (upTan + downTan);
  3871. result.m[0] = xScale;
  3872. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3873. result.m[5] = yScale;
  3874. result.m[6] = result.m[7] = 0.0;
  3875. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3876. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3877. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3878. result.m[10] = -zfar / (znear - zfar);
  3879. result.m[11] = 1.0 * rightHandedFactor;
  3880. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3881. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3882. // result.m[14] = (znear * zfar) / (znear - zfar);
  3883. result._markAsUpdated();
  3884. };
  3885. /**
  3886. * Returns the final transformation matrix : world * view * projection * viewport
  3887. */
  3888. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3889. var cw = viewport.width;
  3890. var ch = viewport.height;
  3891. var cx = viewport.x;
  3892. var cy = viewport.y;
  3893. 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);
  3894. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3895. };
  3896. /**
  3897. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3898. */
  3899. Matrix.GetAsMatrix2x2 = function (matrix) {
  3900. return new Float32Array([
  3901. matrix.m[0], matrix.m[1],
  3902. matrix.m[4], matrix.m[5]
  3903. ]);
  3904. };
  3905. /**
  3906. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3907. */
  3908. Matrix.GetAsMatrix3x3 = function (matrix) {
  3909. return new Float32Array([
  3910. matrix.m[0], matrix.m[1], matrix.m[2],
  3911. matrix.m[4], matrix.m[5], matrix.m[6],
  3912. matrix.m[8], matrix.m[9], matrix.m[10]
  3913. ]);
  3914. };
  3915. /**
  3916. * Compute the transpose of the passed Matrix.
  3917. * Returns a new Matrix.
  3918. */
  3919. Matrix.Transpose = function (matrix) {
  3920. var result = new Matrix();
  3921. Matrix.TransposeToRef(matrix, result);
  3922. return result;
  3923. };
  3924. /**
  3925. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3926. */
  3927. Matrix.TransposeToRef = function (matrix, result) {
  3928. result.m[0] = matrix.m[0];
  3929. result.m[1] = matrix.m[4];
  3930. result.m[2] = matrix.m[8];
  3931. result.m[3] = matrix.m[12];
  3932. result.m[4] = matrix.m[1];
  3933. result.m[5] = matrix.m[5];
  3934. result.m[6] = matrix.m[9];
  3935. result.m[7] = matrix.m[13];
  3936. result.m[8] = matrix.m[2];
  3937. result.m[9] = matrix.m[6];
  3938. result.m[10] = matrix.m[10];
  3939. result.m[11] = matrix.m[14];
  3940. result.m[12] = matrix.m[3];
  3941. result.m[13] = matrix.m[7];
  3942. result.m[14] = matrix.m[11];
  3943. result.m[15] = matrix.m[15];
  3944. };
  3945. /**
  3946. * Returns a new Matrix as the reflection matrix across the passed plane.
  3947. */
  3948. Matrix.Reflection = function (plane) {
  3949. var matrix = new Matrix();
  3950. Matrix.ReflectionToRef(plane, matrix);
  3951. return matrix;
  3952. };
  3953. /**
  3954. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3955. */
  3956. Matrix.ReflectionToRef = function (plane, result) {
  3957. plane.normalize();
  3958. var x = plane.normal.x;
  3959. var y = plane.normal.y;
  3960. var z = plane.normal.z;
  3961. var temp = -2 * x;
  3962. var temp2 = -2 * y;
  3963. var temp3 = -2 * z;
  3964. result.m[0] = (temp * x) + 1;
  3965. result.m[1] = temp2 * x;
  3966. result.m[2] = temp3 * x;
  3967. result.m[3] = 0.0;
  3968. result.m[4] = temp * y;
  3969. result.m[5] = (temp2 * y) + 1;
  3970. result.m[6] = temp3 * y;
  3971. result.m[7] = 0.0;
  3972. result.m[8] = temp * z;
  3973. result.m[9] = temp2 * z;
  3974. result.m[10] = (temp3 * z) + 1;
  3975. result.m[11] = 0.0;
  3976. result.m[12] = temp * plane.d;
  3977. result.m[13] = temp2 * plane.d;
  3978. result.m[14] = temp3 * plane.d;
  3979. result.m[15] = 1.0;
  3980. result._markAsUpdated();
  3981. };
  3982. /**
  3983. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3984. */
  3985. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3986. result.m[0] = xaxis.x;
  3987. result.m[1] = xaxis.y;
  3988. result.m[2] = xaxis.z;
  3989. result.m[3] = 0.0;
  3990. result.m[4] = yaxis.x;
  3991. result.m[5] = yaxis.y;
  3992. result.m[6] = yaxis.z;
  3993. result.m[7] = 0.0;
  3994. result.m[8] = zaxis.x;
  3995. result.m[9] = zaxis.y;
  3996. result.m[10] = zaxis.z;
  3997. result.m[11] = 0.0;
  3998. result.m[12] = 0.0;
  3999. result.m[13] = 0.0;
  4000. result.m[14] = 0.0;
  4001. result.m[15] = 1.0;
  4002. result._markAsUpdated();
  4003. };
  4004. /**
  4005. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4006. */
  4007. Matrix.FromQuaternionToRef = function (quat, result) {
  4008. var xx = quat.x * quat.x;
  4009. var yy = quat.y * quat.y;
  4010. var zz = quat.z * quat.z;
  4011. var xy = quat.x * quat.y;
  4012. var zw = quat.z * quat.w;
  4013. var zx = quat.z * quat.x;
  4014. var yw = quat.y * quat.w;
  4015. var yz = quat.y * quat.z;
  4016. var xw = quat.x * quat.w;
  4017. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4018. result.m[1] = 2.0 * (xy + zw);
  4019. result.m[2] = 2.0 * (zx - yw);
  4020. result.m[3] = 0.0;
  4021. result.m[4] = 2.0 * (xy - zw);
  4022. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4023. result.m[6] = 2.0 * (yz + xw);
  4024. result.m[7] = 0.0;
  4025. result.m[8] = 2.0 * (zx + yw);
  4026. result.m[9] = 2.0 * (yz - xw);
  4027. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4028. result.m[11] = 0.0;
  4029. result.m[12] = 0.0;
  4030. result.m[13] = 0.0;
  4031. result.m[14] = 0.0;
  4032. result.m[15] = 1.0;
  4033. result._markAsUpdated();
  4034. };
  4035. Matrix._tempQuaternion = new Quaternion();
  4036. Matrix._xAxis = Vector3.Zero();
  4037. Matrix._yAxis = Vector3.Zero();
  4038. Matrix._zAxis = Vector3.Zero();
  4039. Matrix._updateFlagSeed = 0;
  4040. Matrix._identityReadOnly = Matrix.Identity();
  4041. return Matrix;
  4042. }());
  4043. BABYLON.Matrix = Matrix;
  4044. var Plane = /** @class */ (function () {
  4045. /**
  4046. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4047. */
  4048. function Plane(a, b, c, d) {
  4049. this.normal = new Vector3(a, b, c);
  4050. this.d = d;
  4051. }
  4052. /**
  4053. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4054. */
  4055. Plane.prototype.asArray = function () {
  4056. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4057. };
  4058. // Methods
  4059. /**
  4060. * Returns a new plane copied from the current Plane.
  4061. */
  4062. Plane.prototype.clone = function () {
  4063. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4064. };
  4065. /**
  4066. * Returns the string "Plane".
  4067. */
  4068. Plane.prototype.getClassName = function () {
  4069. return "Plane";
  4070. };
  4071. /**
  4072. * Returns the Plane hash code.
  4073. */
  4074. Plane.prototype.getHashCode = function () {
  4075. var hash = this.normal.getHashCode();
  4076. hash = (hash * 397) ^ (this.d || 0);
  4077. return hash;
  4078. };
  4079. /**
  4080. * Normalize the current Plane in place.
  4081. * Returns the updated Plane.
  4082. */
  4083. Plane.prototype.normalize = function () {
  4084. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4085. var magnitude = 0.0;
  4086. if (norm !== 0) {
  4087. magnitude = 1.0 / norm;
  4088. }
  4089. this.normal.x *= magnitude;
  4090. this.normal.y *= magnitude;
  4091. this.normal.z *= magnitude;
  4092. this.d *= magnitude;
  4093. return this;
  4094. };
  4095. /**
  4096. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4097. */
  4098. Plane.prototype.transform = function (transformation) {
  4099. var transposedMatrix = Matrix.Transpose(transformation);
  4100. var x = this.normal.x;
  4101. var y = this.normal.y;
  4102. var z = this.normal.z;
  4103. var d = this.d;
  4104. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4105. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4106. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4107. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4108. return new Plane(normalX, normalY, normalZ, finalD);
  4109. };
  4110. /**
  4111. * Returns the dot product (float) of the point coordinates and the plane normal.
  4112. */
  4113. Plane.prototype.dotCoordinate = function (point) {
  4114. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4115. };
  4116. /**
  4117. * Updates the current Plane from the plane defined by the three passed points.
  4118. * Returns the updated Plane.
  4119. */
  4120. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4121. var x1 = point2.x - point1.x;
  4122. var y1 = point2.y - point1.y;
  4123. var z1 = point2.z - point1.z;
  4124. var x2 = point3.x - point1.x;
  4125. var y2 = point3.y - point1.y;
  4126. var z2 = point3.z - point1.z;
  4127. var yz = (y1 * z2) - (z1 * y2);
  4128. var xz = (z1 * x2) - (x1 * z2);
  4129. var xy = (x1 * y2) - (y1 * x2);
  4130. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4131. var invPyth;
  4132. if (pyth !== 0) {
  4133. invPyth = 1.0 / pyth;
  4134. }
  4135. else {
  4136. invPyth = 0.0;
  4137. }
  4138. this.normal.x = yz * invPyth;
  4139. this.normal.y = xz * invPyth;
  4140. this.normal.z = xy * invPyth;
  4141. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4142. return this;
  4143. };
  4144. /**
  4145. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4146. */
  4147. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4148. var dot = Vector3.Dot(this.normal, direction);
  4149. return (dot <= epsilon);
  4150. };
  4151. /**
  4152. * Returns the signed distance (float) from the passed point to the Plane.
  4153. */
  4154. Plane.prototype.signedDistanceTo = function (point) {
  4155. return Vector3.Dot(point, this.normal) + this.d;
  4156. };
  4157. // Statics
  4158. /**
  4159. * Returns a new Plane from the passed array.
  4160. */
  4161. Plane.FromArray = function (array) {
  4162. return new Plane(array[0], array[1], array[2], array[3]);
  4163. };
  4164. /**
  4165. * Returns a new Plane defined by the three passed points.
  4166. */
  4167. Plane.FromPoints = function (point1, point2, point3) {
  4168. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4169. result.copyFromPoints(point1, point2, point3);
  4170. return result;
  4171. };
  4172. /**
  4173. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4174. * Note : the vector "normal" is updated because normalized.
  4175. */
  4176. Plane.FromPositionAndNormal = function (origin, normal) {
  4177. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4178. normal.normalize();
  4179. result.normal = normal;
  4180. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4181. return result;
  4182. };
  4183. /**
  4184. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4185. */
  4186. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4187. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4188. return Vector3.Dot(point, normal) + d;
  4189. };
  4190. return Plane;
  4191. }());
  4192. BABYLON.Plane = Plane;
  4193. var Viewport = /** @class */ (function () {
  4194. /**
  4195. * Creates a Viewport object located at (x, y) and sized (width, height).
  4196. */
  4197. function Viewport(x, y, width, height) {
  4198. this.x = x;
  4199. this.y = y;
  4200. this.width = width;
  4201. this.height = height;
  4202. }
  4203. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4204. if (renderWidthOrEngine.getRenderWidth) {
  4205. var engine = renderWidthOrEngine;
  4206. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4207. }
  4208. var renderWidth = renderWidthOrEngine;
  4209. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4210. };
  4211. /**
  4212. * Returns a new Viewport copied from the current one.
  4213. */
  4214. Viewport.prototype.clone = function () {
  4215. return new Viewport(this.x, this.y, this.width, this.height);
  4216. };
  4217. return Viewport;
  4218. }());
  4219. BABYLON.Viewport = Viewport;
  4220. var Frustum = /** @class */ (function () {
  4221. function Frustum() {
  4222. }
  4223. /**
  4224. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4225. */
  4226. Frustum.GetPlanes = function (transform) {
  4227. var frustumPlanes = [];
  4228. for (var index = 0; index < 6; index++) {
  4229. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4230. }
  4231. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4232. return frustumPlanes;
  4233. };
  4234. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4235. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4236. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4237. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4238. frustumPlane.d = transform.m[15] + transform.m[14];
  4239. frustumPlane.normalize();
  4240. };
  4241. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4242. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4243. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4244. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4245. frustumPlane.d = transform.m[15] - transform.m[14];
  4246. frustumPlane.normalize();
  4247. };
  4248. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4249. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4250. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4251. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4252. frustumPlane.d = transform.m[15] + transform.m[12];
  4253. frustumPlane.normalize();
  4254. };
  4255. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4256. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4257. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4258. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4259. frustumPlane.d = transform.m[15] - transform.m[12];
  4260. frustumPlane.normalize();
  4261. };
  4262. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4263. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4264. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4265. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4266. frustumPlane.d = transform.m[15] - transform.m[13];
  4267. frustumPlane.normalize();
  4268. };
  4269. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4270. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4271. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4272. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4273. frustumPlane.d = transform.m[15] + transform.m[13];
  4274. frustumPlane.normalize();
  4275. };
  4276. /**
  4277. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4278. */
  4279. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4280. // Near
  4281. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4282. // Far
  4283. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4284. // Left
  4285. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4286. // Right
  4287. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4288. // Top
  4289. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4290. // Bottom
  4291. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4292. };
  4293. return Frustum;
  4294. }());
  4295. BABYLON.Frustum = Frustum;
  4296. var Space;
  4297. (function (Space) {
  4298. Space[Space["LOCAL"] = 0] = "LOCAL";
  4299. Space[Space["WORLD"] = 1] = "WORLD";
  4300. Space[Space["BONE"] = 2] = "BONE";
  4301. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4302. var Axis = /** @class */ (function () {
  4303. function Axis() {
  4304. }
  4305. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4306. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4307. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4308. return Axis;
  4309. }());
  4310. BABYLON.Axis = Axis;
  4311. ;
  4312. var BezierCurve = /** @class */ (function () {
  4313. function BezierCurve() {
  4314. }
  4315. /**
  4316. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4317. */
  4318. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4319. // Extract X (which is equal to time here)
  4320. var f0 = 1 - 3 * x2 + 3 * x1;
  4321. var f1 = 3 * x2 - 6 * x1;
  4322. var f2 = 3 * x1;
  4323. var refinedT = t;
  4324. for (var i = 0; i < 5; i++) {
  4325. var refinedT2 = refinedT * refinedT;
  4326. var refinedT3 = refinedT2 * refinedT;
  4327. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4328. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4329. refinedT -= (x - t) * slope;
  4330. refinedT = Math.min(1, Math.max(0, refinedT));
  4331. }
  4332. // Resolve cubic bezier for the given x
  4333. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4334. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4335. Math.pow(refinedT, 3);
  4336. };
  4337. return BezierCurve;
  4338. }());
  4339. BABYLON.BezierCurve = BezierCurve;
  4340. var Orientation;
  4341. (function (Orientation) {
  4342. Orientation[Orientation["CW"] = 0] = "CW";
  4343. Orientation[Orientation["CCW"] = 1] = "CCW";
  4344. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4345. var Angle = /** @class */ (function () {
  4346. /**
  4347. * Creates an Angle object of "radians" radians (float).
  4348. */
  4349. function Angle(radians) {
  4350. var _this = this;
  4351. /**
  4352. * Returns the Angle value in degrees (float).
  4353. */
  4354. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4355. /**
  4356. * Returns the Angle value in radians (float).
  4357. */
  4358. this.radians = function () { return _this._radians; };
  4359. this._radians = radians;
  4360. if (this._radians < 0.0)
  4361. this._radians += (2.0 * Math.PI);
  4362. }
  4363. /**
  4364. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4365. */
  4366. Angle.BetweenTwoPoints = function (a, b) {
  4367. var delta = b.subtract(a);
  4368. var theta = Math.atan2(delta.y, delta.x);
  4369. return new Angle(theta);
  4370. };
  4371. /**
  4372. * Returns a new Angle object from the passed float in radians.
  4373. */
  4374. Angle.FromRadians = function (radians) {
  4375. return new Angle(radians);
  4376. };
  4377. /**
  4378. * Returns a new Angle object from the passed float in degrees.
  4379. */
  4380. Angle.FromDegrees = function (degrees) {
  4381. return new Angle(degrees * Math.PI / 180.0);
  4382. };
  4383. return Angle;
  4384. }());
  4385. BABYLON.Angle = Angle;
  4386. var Arc2 = /** @class */ (function () {
  4387. /**
  4388. * Creates an Arc object from the three passed points : start, middle and end.
  4389. */
  4390. function Arc2(startPoint, midPoint, endPoint) {
  4391. this.startPoint = startPoint;
  4392. this.midPoint = midPoint;
  4393. this.endPoint = endPoint;
  4394. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4395. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4396. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4397. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4398. 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);
  4399. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4400. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4401. var a1 = this.startAngle.degrees();
  4402. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4403. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4404. // angles correction
  4405. if (a2 - a1 > +180.0)
  4406. a2 -= 360.0;
  4407. if (a2 - a1 < -180.0)
  4408. a2 += 360.0;
  4409. if (a3 - a2 > +180.0)
  4410. a3 -= 360.0;
  4411. if (a3 - a2 < -180.0)
  4412. a3 += 360.0;
  4413. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4414. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4415. }
  4416. return Arc2;
  4417. }());
  4418. BABYLON.Arc2 = Arc2;
  4419. var Path2 = /** @class */ (function () {
  4420. /**
  4421. * Creates a Path2 object from the starting 2D coordinates x and y.
  4422. */
  4423. function Path2(x, y) {
  4424. this._points = new Array();
  4425. this._length = 0.0;
  4426. this.closed = false;
  4427. this._points.push(new Vector2(x, y));
  4428. }
  4429. /**
  4430. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4431. * Returns the updated Path2.
  4432. */
  4433. Path2.prototype.addLineTo = function (x, y) {
  4434. if (closed) {
  4435. //Tools.Error("cannot add lines to closed paths");
  4436. return this;
  4437. }
  4438. var newPoint = new Vector2(x, y);
  4439. var previousPoint = this._points[this._points.length - 1];
  4440. this._points.push(newPoint);
  4441. this._length += newPoint.subtract(previousPoint).length();
  4442. return this;
  4443. };
  4444. /**
  4445. * 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.
  4446. * Returns the updated Path2.
  4447. */
  4448. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4449. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4450. if (closed) {
  4451. //Tools.Error("cannot add arcs to closed paths");
  4452. return this;
  4453. }
  4454. var startPoint = this._points[this._points.length - 1];
  4455. var midPoint = new Vector2(midX, midY);
  4456. var endPoint = new Vector2(endX, endY);
  4457. var arc = new Arc2(startPoint, midPoint, endPoint);
  4458. var increment = arc.angle.radians() / numberOfSegments;
  4459. if (arc.orientation === Orientation.CW)
  4460. increment *= -1;
  4461. var currentAngle = arc.startAngle.radians() + increment;
  4462. for (var i = 0; i < numberOfSegments; i++) {
  4463. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4464. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4465. this.addLineTo(x, y);
  4466. currentAngle += increment;
  4467. }
  4468. return this;
  4469. };
  4470. /**
  4471. * Closes the Path2.
  4472. * Returns the Path2.
  4473. */
  4474. Path2.prototype.close = function () {
  4475. this.closed = true;
  4476. return this;
  4477. };
  4478. /**
  4479. * Returns the Path2 total length (float).
  4480. */
  4481. Path2.prototype.length = function () {
  4482. var result = this._length;
  4483. if (!this.closed) {
  4484. var lastPoint = this._points[this._points.length - 1];
  4485. var firstPoint = this._points[0];
  4486. result += (firstPoint.subtract(lastPoint).length());
  4487. }
  4488. return result;
  4489. };
  4490. /**
  4491. * Returns the Path2 internal array of points.
  4492. */
  4493. Path2.prototype.getPoints = function () {
  4494. return this._points;
  4495. };
  4496. /**
  4497. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4498. */
  4499. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4500. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4501. //Tools.Error("normalized length position should be between 0 and 1.");
  4502. return Vector2.Zero();
  4503. }
  4504. var lengthPosition = normalizedLengthPosition * this.length();
  4505. var previousOffset = 0;
  4506. for (var i = 0; i < this._points.length; i++) {
  4507. var j = (i + 1) % this._points.length;
  4508. var a = this._points[i];
  4509. var b = this._points[j];
  4510. var bToA = b.subtract(a);
  4511. var nextOffset = (bToA.length() + previousOffset);
  4512. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4513. var dir = bToA.normalize();
  4514. var localOffset = lengthPosition - previousOffset;
  4515. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4516. }
  4517. previousOffset = nextOffset;
  4518. }
  4519. //Tools.Error("internal error");
  4520. return Vector2.Zero();
  4521. };
  4522. /**
  4523. * Returns a new Path2 starting at the coordinates (x, y).
  4524. */
  4525. Path2.StartingAt = function (x, y) {
  4526. return new Path2(x, y);
  4527. };
  4528. return Path2;
  4529. }());
  4530. BABYLON.Path2 = Path2;
  4531. var Path3D = /** @class */ (function () {
  4532. /**
  4533. * new Path3D(path, normal, raw)
  4534. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4535. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4536. * path : an array of Vector3, the curve axis of the Path3D
  4537. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4538. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4539. */
  4540. function Path3D(path, firstNormal, raw) {
  4541. if (firstNormal === void 0) { firstNormal = null; }
  4542. this.path = path;
  4543. this._curve = new Array();
  4544. this._distances = new Array();
  4545. this._tangents = new Array();
  4546. this._normals = new Array();
  4547. this._binormals = new Array();
  4548. for (var p = 0; p < path.length; p++) {
  4549. this._curve[p] = path[p].clone(); // hard copy
  4550. }
  4551. this._raw = raw || false;
  4552. this._compute(firstNormal);
  4553. }
  4554. /**
  4555. * Returns the Path3D array of successive Vector3 designing its curve.
  4556. */
  4557. Path3D.prototype.getCurve = function () {
  4558. return this._curve;
  4559. };
  4560. /**
  4561. * Returns an array populated with tangent vectors on each Path3D curve point.
  4562. */
  4563. Path3D.prototype.getTangents = function () {
  4564. return this._tangents;
  4565. };
  4566. /**
  4567. * Returns an array populated with normal vectors on each Path3D curve point.
  4568. */
  4569. Path3D.prototype.getNormals = function () {
  4570. return this._normals;
  4571. };
  4572. /**
  4573. * Returns an array populated with binormal vectors on each Path3D curve point.
  4574. */
  4575. Path3D.prototype.getBinormals = function () {
  4576. return this._binormals;
  4577. };
  4578. /**
  4579. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4580. */
  4581. Path3D.prototype.getDistances = function () {
  4582. return this._distances;
  4583. };
  4584. /**
  4585. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4586. * Returns the same object updated.
  4587. */
  4588. Path3D.prototype.update = function (path, firstNormal) {
  4589. if (firstNormal === void 0) { firstNormal = null; }
  4590. for (var p = 0; p < path.length; p++) {
  4591. this._curve[p].x = path[p].x;
  4592. this._curve[p].y = path[p].y;
  4593. this._curve[p].z = path[p].z;
  4594. }
  4595. this._compute(firstNormal);
  4596. return this;
  4597. };
  4598. // private function compute() : computes tangents, normals and binormals
  4599. Path3D.prototype._compute = function (firstNormal) {
  4600. var l = this._curve.length;
  4601. // first and last tangents
  4602. this._tangents[0] = this._getFirstNonNullVector(0);
  4603. if (!this._raw) {
  4604. this._tangents[0].normalize();
  4605. }
  4606. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4607. if (!this._raw) {
  4608. this._tangents[l - 1].normalize();
  4609. }
  4610. // normals and binormals at first point : arbitrary vector with _normalVector()
  4611. var tg0 = this._tangents[0];
  4612. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4613. this._normals[0] = pp0;
  4614. if (!this._raw) {
  4615. this._normals[0].normalize();
  4616. }
  4617. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4618. if (!this._raw) {
  4619. this._binormals[0].normalize();
  4620. }
  4621. this._distances[0] = 0.0;
  4622. // normals and binormals : next points
  4623. var prev; // previous vector (segment)
  4624. var cur; // current vector (segment)
  4625. var curTang; // current tangent
  4626. // previous normal
  4627. var prevBinor; // previous binormal
  4628. for (var i = 1; i < l; i++) {
  4629. // tangents
  4630. prev = this._getLastNonNullVector(i);
  4631. if (i < l - 1) {
  4632. cur = this._getFirstNonNullVector(i);
  4633. this._tangents[i] = prev.add(cur);
  4634. this._tangents[i].normalize();
  4635. }
  4636. this._distances[i] = this._distances[i - 1] + prev.length();
  4637. // normals and binormals
  4638. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4639. curTang = this._tangents[i];
  4640. prevBinor = this._binormals[i - 1];
  4641. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4642. if (!this._raw) {
  4643. this._normals[i].normalize();
  4644. }
  4645. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4646. if (!this._raw) {
  4647. this._binormals[i].normalize();
  4648. }
  4649. }
  4650. };
  4651. // private function getFirstNonNullVector(index)
  4652. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4653. Path3D.prototype._getFirstNonNullVector = function (index) {
  4654. var i = 1;
  4655. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4656. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4657. i++;
  4658. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4659. }
  4660. return nNVector;
  4661. };
  4662. // private function getLastNonNullVector(index)
  4663. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4664. Path3D.prototype._getLastNonNullVector = function (index) {
  4665. var i = 1;
  4666. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4667. while (nLVector.length() === 0 && index > i + 1) {
  4668. i++;
  4669. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4670. }
  4671. return nLVector;
  4672. };
  4673. // private function normalVector(v0, vt, va) :
  4674. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4675. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4676. Path3D.prototype._normalVector = function (v0, vt, va) {
  4677. var normal0;
  4678. var tgl = vt.length();
  4679. if (tgl === 0.0) {
  4680. tgl = 1.0;
  4681. }
  4682. if (va === undefined || va === null) {
  4683. var point;
  4684. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4685. point = new Vector3(0.0, -1.0, 0.0);
  4686. }
  4687. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4688. point = new Vector3(1.0, 0.0, 0.0);
  4689. }
  4690. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4691. point = new Vector3(0.0, 0.0, 1.0);
  4692. }
  4693. else {
  4694. point = Vector3.Zero();
  4695. }
  4696. normal0 = Vector3.Cross(vt, point);
  4697. }
  4698. else {
  4699. normal0 = Vector3.Cross(vt, va);
  4700. Vector3.CrossToRef(normal0, vt, normal0);
  4701. }
  4702. normal0.normalize();
  4703. return normal0;
  4704. };
  4705. return Path3D;
  4706. }());
  4707. BABYLON.Path3D = Path3D;
  4708. var Curve3 = /** @class */ (function () {
  4709. /**
  4710. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4711. * A Curve3 is designed from a series of successive Vector3.
  4712. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4713. */
  4714. function Curve3(points) {
  4715. this._length = 0.0;
  4716. this._points = points;
  4717. this._length = this._computeLength(points);
  4718. }
  4719. /**
  4720. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4721. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4722. * @param v1 (Vector3) the control point
  4723. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4724. * @param nbPoints (integer) the wanted number of points in the curve
  4725. */
  4726. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4727. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4728. var bez = new Array();
  4729. var equation = function (t, val0, val1, val2) {
  4730. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4731. return res;
  4732. };
  4733. for (var i = 0; i <= nbPoints; i++) {
  4734. 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)));
  4735. }
  4736. return new Curve3(bez);
  4737. };
  4738. /**
  4739. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4740. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4741. * @param v1 (Vector3) the first control point
  4742. * @param v2 (Vector3) the second control point
  4743. * @param v3 (Vector3) the end point of the Cubic Bezier
  4744. * @param nbPoints (integer) the wanted number of points in the curve
  4745. */
  4746. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4747. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4748. var bez = new Array();
  4749. var equation = function (t, val0, val1, val2, val3) {
  4750. 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;
  4751. return res;
  4752. };
  4753. for (var i = 0; i <= nbPoints; i++) {
  4754. 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)));
  4755. }
  4756. return new Curve3(bez);
  4757. };
  4758. /**
  4759. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4760. * @param p1 (Vector3) the origin point of the Hermite Spline
  4761. * @param t1 (Vector3) the tangent vector at the origin point
  4762. * @param p2 (Vector3) the end point of the Hermite Spline
  4763. * @param t2 (Vector3) the tangent vector at the end point
  4764. * @param nbPoints (integer) the wanted number of points in the curve
  4765. */
  4766. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4767. var hermite = new Array();
  4768. var step = 1.0 / nbPoints;
  4769. for (var i = 0; i <= nbPoints; i++) {
  4770. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4771. }
  4772. return new Curve3(hermite);
  4773. };
  4774. /**
  4775. * Returns a Curve3 object along a CatmullRom Spline curve :
  4776. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4777. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4778. */
  4779. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4780. var totalPoints = new Array();
  4781. totalPoints.push(points[0].clone());
  4782. Array.prototype.push.apply(totalPoints, points);
  4783. totalPoints.push(points[points.length - 1].clone());
  4784. var catmullRom = new Array();
  4785. var step = 1.0 / nbPoints;
  4786. var amount = 0.0;
  4787. for (var i = 0; i < totalPoints.length - 3; i++) {
  4788. amount = 0;
  4789. for (var c = 0; c < nbPoints; c++) {
  4790. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4791. amount += step;
  4792. }
  4793. }
  4794. i--;
  4795. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4796. return new Curve3(catmullRom);
  4797. };
  4798. /**
  4799. * Returns the Curve3 stored array of successive Vector3
  4800. */
  4801. Curve3.prototype.getPoints = function () {
  4802. return this._points;
  4803. };
  4804. /**
  4805. * Returns the computed length (float) of the curve.
  4806. */
  4807. Curve3.prototype.length = function () {
  4808. return this._length;
  4809. };
  4810. /**
  4811. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4812. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4813. * curveA and curveB keep unchanged.
  4814. */
  4815. Curve3.prototype.continue = function (curve) {
  4816. var lastPoint = this._points[this._points.length - 1];
  4817. var continuedPoints = this._points.slice();
  4818. var curvePoints = curve.getPoints();
  4819. for (var i = 1; i < curvePoints.length; i++) {
  4820. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4821. }
  4822. var continuedCurve = new Curve3(continuedPoints);
  4823. return continuedCurve;
  4824. };
  4825. Curve3.prototype._computeLength = function (path) {
  4826. var l = 0;
  4827. for (var i = 1; i < path.length; i++) {
  4828. l += (path[i].subtract(path[i - 1])).length();
  4829. }
  4830. return l;
  4831. };
  4832. return Curve3;
  4833. }());
  4834. BABYLON.Curve3 = Curve3;
  4835. // Vertex formats
  4836. var PositionNormalVertex = /** @class */ (function () {
  4837. function PositionNormalVertex(position, normal) {
  4838. if (position === void 0) { position = Vector3.Zero(); }
  4839. if (normal === void 0) { normal = Vector3.Up(); }
  4840. this.position = position;
  4841. this.normal = normal;
  4842. }
  4843. PositionNormalVertex.prototype.clone = function () {
  4844. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4845. };
  4846. return PositionNormalVertex;
  4847. }());
  4848. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4849. var PositionNormalTextureVertex = /** @class */ (function () {
  4850. function PositionNormalTextureVertex(position, normal, uv) {
  4851. if (position === void 0) { position = Vector3.Zero(); }
  4852. if (normal === void 0) { normal = Vector3.Up(); }
  4853. if (uv === void 0) { uv = Vector2.Zero(); }
  4854. this.position = position;
  4855. this.normal = normal;
  4856. this.uv = uv;
  4857. }
  4858. PositionNormalTextureVertex.prototype.clone = function () {
  4859. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4860. };
  4861. return PositionNormalTextureVertex;
  4862. }());
  4863. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4864. // Temporary pre-allocated objects for engine internal use
  4865. // usage in any internal function :
  4866. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4867. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4868. var Tmp = /** @class */ (function () {
  4869. function Tmp() {
  4870. }
  4871. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4872. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4873. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4874. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4875. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4876. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4877. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4878. Matrix.Zero(), Matrix.Zero(),
  4879. Matrix.Zero(), Matrix.Zero(),
  4880. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4881. return Tmp;
  4882. }());
  4883. BABYLON.Tmp = Tmp;
  4884. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4885. var MathTmp = /** @class */ (function () {
  4886. function MathTmp() {
  4887. }
  4888. MathTmp.Vector3 = [Vector3.Zero()];
  4889. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4890. MathTmp.Quaternion = [Quaternion.Zero()];
  4891. return MathTmp;
  4892. }());
  4893. })(BABYLON || (BABYLON = {}));
  4894. //# sourceMappingURL=babylon.math.js.map
  4895. var BABYLON;
  4896. (function (BABYLON) {
  4897. var Scalar = /** @class */ (function () {
  4898. function Scalar() {
  4899. }
  4900. /**
  4901. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4902. */
  4903. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4904. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4905. var num = a - b;
  4906. return -epsilon <= num && num <= epsilon;
  4907. };
  4908. /**
  4909. * Returns a string : the upper case translation of the number i to hexadecimal.
  4910. */
  4911. Scalar.ToHex = function (i) {
  4912. var str = i.toString(16);
  4913. if (i <= 15) {
  4914. return ("0" + str).toUpperCase();
  4915. }
  4916. return str.toUpperCase();
  4917. };
  4918. /**
  4919. * Returns -1 if value is negative and +1 is value is positive.
  4920. * Returns the value itself if it's equal to zero.
  4921. */
  4922. Scalar.Sign = function (value) {
  4923. value = +value; // convert to a number
  4924. if (value === 0 || isNaN(value))
  4925. return value;
  4926. return value > 0 ? 1 : -1;
  4927. };
  4928. /**
  4929. * Returns the value itself if it's between min and max.
  4930. * Returns min if the value is lower than min.
  4931. * Returns max if the value is greater than max.
  4932. */
  4933. Scalar.Clamp = function (value, min, max) {
  4934. if (min === void 0) { min = 0; }
  4935. if (max === void 0) { max = 1; }
  4936. return Math.min(max, Math.max(min, value));
  4937. };
  4938. /**
  4939. * Returns the log2 of value.
  4940. */
  4941. Scalar.Log2 = function (value) {
  4942. return Math.log(value) * Math.LOG2E;
  4943. };
  4944. /**
  4945. * Loops the value, so that it is never larger than length and never smaller than 0.
  4946. *
  4947. * This is similar to the modulo operator but it works with floating point numbers.
  4948. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4949. * With t = 5 and length = 2.5, the result would be 0.0.
  4950. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4951. */
  4952. Scalar.Repeat = function (value, length) {
  4953. return value - Math.floor(value / length) * length;
  4954. };
  4955. /**
  4956. * Normalize the value between 0.0 and 1.0 using min and max values
  4957. */
  4958. Scalar.Normalize = function (value, min, max) {
  4959. return (value - min) / (max - min);
  4960. };
  4961. /**
  4962. * Denormalize the value from 0.0 and 1.0 using min and max values
  4963. */
  4964. Scalar.Denormalize = function (normalized, min, max) {
  4965. return (normalized * (max - min) + min);
  4966. };
  4967. /**
  4968. * Calculates the shortest difference between two given angles given in degrees.
  4969. */
  4970. Scalar.DeltaAngle = function (current, target) {
  4971. var num = Scalar.Repeat(target - current, 360.0);
  4972. if (num > 180.0) {
  4973. num -= 360.0;
  4974. }
  4975. return num;
  4976. };
  4977. /**
  4978. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4979. *
  4980. * The returned value will move back and forth between 0 and length
  4981. */
  4982. Scalar.PingPong = function (tx, length) {
  4983. var t = Scalar.Repeat(tx, length * 2.0);
  4984. return length - Math.abs(t - length);
  4985. };
  4986. /**
  4987. * Interpolates between min and max with smoothing at the limits.
  4988. *
  4989. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4990. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4991. */
  4992. Scalar.SmoothStep = function (from, to, tx) {
  4993. var t = Scalar.Clamp(tx);
  4994. t = -2.0 * t * t * t + 3.0 * t * t;
  4995. return to * t + from * (1.0 - t);
  4996. };
  4997. /**
  4998. * Moves a value current towards target.
  4999. *
  5000. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5001. * Negative values of maxDelta pushes the value away from target.
  5002. */
  5003. Scalar.MoveTowards = function (current, target, maxDelta) {
  5004. var result = 0;
  5005. if (Math.abs(target - current) <= maxDelta) {
  5006. result = target;
  5007. }
  5008. else {
  5009. result = current + Scalar.Sign(target - current) * maxDelta;
  5010. }
  5011. return result;
  5012. };
  5013. /**
  5014. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5015. *
  5016. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5017. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5018. */
  5019. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5020. var num = Scalar.DeltaAngle(current, target);
  5021. var result = 0;
  5022. if (-maxDelta < num && num < maxDelta) {
  5023. result = target;
  5024. }
  5025. else {
  5026. target = current + num;
  5027. result = Scalar.MoveTowards(current, target, maxDelta);
  5028. }
  5029. return result;
  5030. };
  5031. /**
  5032. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5033. */
  5034. Scalar.Lerp = function (start, end, amount) {
  5035. return start + ((end - start) * amount);
  5036. };
  5037. /**
  5038. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5039. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5040. */
  5041. Scalar.LerpAngle = function (start, end, amount) {
  5042. var num = Scalar.Repeat(end - start, 360.0);
  5043. if (num > 180.0) {
  5044. num -= 360.0;
  5045. }
  5046. return start + num * Scalar.Clamp(amount);
  5047. };
  5048. /**
  5049. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5050. */
  5051. Scalar.InverseLerp = function (a, b, value) {
  5052. var result = 0;
  5053. if (a != b) {
  5054. result = Scalar.Clamp((value - a) / (b - a));
  5055. }
  5056. else {
  5057. result = 0.0;
  5058. }
  5059. return result;
  5060. };
  5061. /**
  5062. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5063. */
  5064. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5065. var squared = amount * amount;
  5066. var cubed = amount * squared;
  5067. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5068. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5069. var part3 = (cubed - (2.0 * squared)) + amount;
  5070. var part4 = cubed - squared;
  5071. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5072. };
  5073. /**
  5074. * Returns a random float number between and min and max values
  5075. */
  5076. Scalar.RandomRange = function (min, max) {
  5077. if (min === max)
  5078. return min;
  5079. return ((Math.random() * (max - min)) + min);
  5080. };
  5081. /**
  5082. * This function returns percentage of a number in a given range.
  5083. *
  5084. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5085. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5086. */
  5087. Scalar.RangeToPercent = function (number, min, max) {
  5088. return ((number - min) / (max - min));
  5089. };
  5090. /**
  5091. * This function returns number that corresponds to the percentage in a given range.
  5092. *
  5093. * PercentToRange(0.34,0,100) will return 34.
  5094. */
  5095. Scalar.PercentToRange = function (percent, min, max) {
  5096. return ((max - min) * percent + min);
  5097. };
  5098. return Scalar;
  5099. }());
  5100. BABYLON.Scalar = Scalar;
  5101. })(BABYLON || (BABYLON = {}));
  5102. //# sourceMappingURL=babylon.math.scalar.js.map
  5103. //# sourceMappingURL=babylon.mixins.js.map
  5104. var BABYLON;
  5105. (function (BABYLON) {
  5106. var __decoratorInitialStore = {};
  5107. var __mergedStore = {};
  5108. var _copySource = function (creationFunction, source, instanciate) {
  5109. var destination = creationFunction();
  5110. // Tags
  5111. if (BABYLON.Tags) {
  5112. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5113. }
  5114. var classStore = getMergedStore(destination);
  5115. // Properties
  5116. for (var property in classStore) {
  5117. var propertyDescriptor = classStore[property];
  5118. var sourceProperty = source[property];
  5119. var propertyType = propertyDescriptor.type;
  5120. if (sourceProperty !== undefined && sourceProperty !== null) {
  5121. switch (propertyType) {
  5122. case 0: // Value
  5123. case 6:// Mesh reference
  5124. destination[property] = sourceProperty;
  5125. break;
  5126. case 1:// Texture
  5127. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5128. break;
  5129. case 2: // Color3
  5130. case 3: // FresnelParameters
  5131. case 4: // Vector2
  5132. case 5: // Vector3
  5133. case 7:// Color Curves
  5134. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5135. break;
  5136. }
  5137. }
  5138. }
  5139. return destination;
  5140. };
  5141. function getDirectStore(target) {
  5142. var classKey = target.getClassName();
  5143. if (!__decoratorInitialStore[classKey]) {
  5144. __decoratorInitialStore[classKey] = {};
  5145. }
  5146. return __decoratorInitialStore[classKey];
  5147. }
  5148. /**
  5149. * Return the list of properties flagged as serializable
  5150. * @param target: host object
  5151. */
  5152. function getMergedStore(target) {
  5153. var classKey = target.getClassName();
  5154. if (__mergedStore[classKey]) {
  5155. return __mergedStore[classKey];
  5156. }
  5157. __mergedStore[classKey] = {};
  5158. var store = __mergedStore[classKey];
  5159. var currentTarget = target;
  5160. var currentKey = classKey;
  5161. while (currentKey) {
  5162. var initialStore = __decoratorInitialStore[currentKey];
  5163. for (var property in initialStore) {
  5164. store[property] = initialStore[property];
  5165. }
  5166. var parent_1 = void 0;
  5167. var done = false;
  5168. do {
  5169. parent_1 = Object.getPrototypeOf(currentTarget);
  5170. if (!parent_1.getClassName) {
  5171. done = true;
  5172. break;
  5173. }
  5174. if (parent_1.getClassName() !== currentKey) {
  5175. break;
  5176. }
  5177. currentTarget = parent_1;
  5178. } while (parent_1);
  5179. if (done) {
  5180. break;
  5181. }
  5182. currentKey = parent_1.getClassName();
  5183. currentTarget = parent_1;
  5184. }
  5185. return store;
  5186. }
  5187. function generateSerializableMember(type, sourceName) {
  5188. return function (target, propertyKey) {
  5189. var classStore = getDirectStore(target);
  5190. if (!classStore[propertyKey]) {
  5191. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5192. }
  5193. };
  5194. }
  5195. function generateExpandMember(setCallback, targetKey) {
  5196. if (targetKey === void 0) { targetKey = null; }
  5197. return function (target, propertyKey) {
  5198. var key = targetKey || ("_" + propertyKey);
  5199. Object.defineProperty(target, propertyKey, {
  5200. get: function () {
  5201. return this[key];
  5202. },
  5203. set: function (value) {
  5204. if (this[key] === value) {
  5205. return;
  5206. }
  5207. this[key] = value;
  5208. target[setCallback].apply(this);
  5209. },
  5210. enumerable: true,
  5211. configurable: true
  5212. });
  5213. };
  5214. }
  5215. function expandToProperty(callback, targetKey) {
  5216. if (targetKey === void 0) { targetKey = null; }
  5217. return generateExpandMember(callback, targetKey);
  5218. }
  5219. BABYLON.expandToProperty = expandToProperty;
  5220. function serialize(sourceName) {
  5221. return generateSerializableMember(0, sourceName); // value member
  5222. }
  5223. BABYLON.serialize = serialize;
  5224. function serializeAsTexture(sourceName) {
  5225. return generateSerializableMember(1, sourceName); // texture member
  5226. }
  5227. BABYLON.serializeAsTexture = serializeAsTexture;
  5228. function serializeAsColor3(sourceName) {
  5229. return generateSerializableMember(2, sourceName); // color3 member
  5230. }
  5231. BABYLON.serializeAsColor3 = serializeAsColor3;
  5232. function serializeAsFresnelParameters(sourceName) {
  5233. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5234. }
  5235. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5236. function serializeAsVector2(sourceName) {
  5237. return generateSerializableMember(4, sourceName); // vector2 member
  5238. }
  5239. BABYLON.serializeAsVector2 = serializeAsVector2;
  5240. function serializeAsVector3(sourceName) {
  5241. return generateSerializableMember(5, sourceName); // vector3 member
  5242. }
  5243. BABYLON.serializeAsVector3 = serializeAsVector3;
  5244. function serializeAsMeshReference(sourceName) {
  5245. return generateSerializableMember(6, sourceName); // mesh reference member
  5246. }
  5247. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5248. function serializeAsColorCurves(sourceName) {
  5249. return generateSerializableMember(7, sourceName); // color curves
  5250. }
  5251. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5252. function serializeAsColor4(sourceName) {
  5253. return generateSerializableMember(8, sourceName); // color 4
  5254. }
  5255. BABYLON.serializeAsColor4 = serializeAsColor4;
  5256. function serializeAsImageProcessingConfiguration(sourceName) {
  5257. return generateSerializableMember(9, sourceName); // image processing
  5258. }
  5259. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5260. var SerializationHelper = /** @class */ (function () {
  5261. function SerializationHelper() {
  5262. }
  5263. SerializationHelper.Serialize = function (entity, serializationObject) {
  5264. if (!serializationObject) {
  5265. serializationObject = {};
  5266. }
  5267. // Tags
  5268. if (BABYLON.Tags) {
  5269. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5270. }
  5271. var serializedProperties = getMergedStore(entity);
  5272. // Properties
  5273. for (var property in serializedProperties) {
  5274. var propertyDescriptor = serializedProperties[property];
  5275. var targetPropertyName = propertyDescriptor.sourceName || property;
  5276. var propertyType = propertyDescriptor.type;
  5277. var sourceProperty = entity[property];
  5278. if (sourceProperty !== undefined && sourceProperty !== null) {
  5279. switch (propertyType) {
  5280. case 0:// Value
  5281. serializationObject[targetPropertyName] = sourceProperty;
  5282. break;
  5283. case 1:// Texture
  5284. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5285. break;
  5286. case 2:// Color3
  5287. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5288. break;
  5289. case 3:// FresnelParameters
  5290. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5291. break;
  5292. case 4:// Vector2
  5293. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5294. break;
  5295. case 5:// Vector3
  5296. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5297. break;
  5298. case 6:// Mesh reference
  5299. serializationObject[targetPropertyName] = sourceProperty.id;
  5300. break;
  5301. case 7:// Color Curves
  5302. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5303. break;
  5304. case 8:// Color 4
  5305. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5306. break;
  5307. case 9:// Image Processing
  5308. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5309. break;
  5310. }
  5311. }
  5312. }
  5313. return serializationObject;
  5314. };
  5315. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5316. if (rootUrl === void 0) { rootUrl = null; }
  5317. var destination = creationFunction();
  5318. if (!rootUrl) {
  5319. rootUrl = "";
  5320. }
  5321. // Tags
  5322. if (BABYLON.Tags) {
  5323. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5324. }
  5325. var classStore = getMergedStore(destination);
  5326. // Properties
  5327. for (var property in classStore) {
  5328. var propertyDescriptor = classStore[property];
  5329. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5330. var propertyType = propertyDescriptor.type;
  5331. if (sourceProperty !== undefined && sourceProperty !== null) {
  5332. var dest = destination;
  5333. switch (propertyType) {
  5334. case 0:// Value
  5335. dest[property] = sourceProperty;
  5336. break;
  5337. case 1:// Texture
  5338. if (scene) {
  5339. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5340. }
  5341. break;
  5342. case 2:// Color3
  5343. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5344. break;
  5345. case 3:// FresnelParameters
  5346. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5347. break;
  5348. case 4:// Vector2
  5349. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5350. break;
  5351. case 5:// Vector3
  5352. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5353. break;
  5354. case 6:// Mesh reference
  5355. if (scene) {
  5356. dest[property] = scene.getLastMeshByID(sourceProperty);
  5357. }
  5358. break;
  5359. case 7:// Color Curves
  5360. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5361. break;
  5362. case 8:// Color 4
  5363. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5364. break;
  5365. case 9:// Image Processing
  5366. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5367. break;
  5368. }
  5369. }
  5370. }
  5371. return destination;
  5372. };
  5373. SerializationHelper.Clone = function (creationFunction, source) {
  5374. return _copySource(creationFunction, source, false);
  5375. };
  5376. SerializationHelper.Instanciate = function (creationFunction, source) {
  5377. return _copySource(creationFunction, source, true);
  5378. };
  5379. return SerializationHelper;
  5380. }());
  5381. BABYLON.SerializationHelper = SerializationHelper;
  5382. })(BABYLON || (BABYLON = {}));
  5383. //# sourceMappingURL=babylon.decorators.js.map
  5384. var BABYLON;
  5385. (function (BABYLON) {
  5386. /**
  5387. * A class serves as a medium between the observable and its observers
  5388. */
  5389. var EventState = /** @class */ (function () {
  5390. /**
  5391. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5392. */
  5393. function EventState(mask, skipNextObservers, target, currentTarget) {
  5394. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5395. this.initalize(mask, skipNextObservers, target, currentTarget);
  5396. }
  5397. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5398. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5399. this.mask = mask;
  5400. this.skipNextObservers = skipNextObservers;
  5401. this.target = target;
  5402. this.currentTarget = currentTarget;
  5403. return this;
  5404. };
  5405. return EventState;
  5406. }());
  5407. BABYLON.EventState = EventState;
  5408. /**
  5409. * Represent an Observer registered to a given Observable object.
  5410. */
  5411. var Observer = /** @class */ (function () {
  5412. function Observer(callback, mask, scope) {
  5413. if (scope === void 0) { scope = null; }
  5414. this.callback = callback;
  5415. this.mask = mask;
  5416. this.scope = scope;
  5417. }
  5418. return Observer;
  5419. }());
  5420. BABYLON.Observer = Observer;
  5421. /**
  5422. * Represent a list of observers registered to multiple Observables object.
  5423. */
  5424. var MultiObserver = /** @class */ (function () {
  5425. function MultiObserver() {
  5426. }
  5427. MultiObserver.prototype.dispose = function () {
  5428. if (this._observers && this._observables) {
  5429. for (var index = 0; index < this._observers.length; index++) {
  5430. this._observables[index].remove(this._observers[index]);
  5431. }
  5432. }
  5433. this._observers = null;
  5434. this._observables = null;
  5435. };
  5436. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5437. if (mask === void 0) { mask = -1; }
  5438. if (scope === void 0) { scope = null; }
  5439. var result = new MultiObserver();
  5440. result._observers = new Array();
  5441. result._observables = observables;
  5442. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5443. var observable = observables_1[_i];
  5444. var observer = observable.add(callback, mask, false, scope);
  5445. if (observer) {
  5446. result._observers.push(observer);
  5447. }
  5448. }
  5449. return result;
  5450. };
  5451. return MultiObserver;
  5452. }());
  5453. BABYLON.MultiObserver = MultiObserver;
  5454. /**
  5455. * The Observable class is a simple implementation of the Observable pattern.
  5456. * 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.
  5457. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5458. * 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).
  5459. * 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.
  5460. */
  5461. var Observable = /** @class */ (function () {
  5462. function Observable(onObserverAdded) {
  5463. this._observers = new Array();
  5464. this._eventState = new EventState(0);
  5465. if (onObserverAdded) {
  5466. this._onObserverAdded = onObserverAdded;
  5467. }
  5468. }
  5469. /**
  5470. * Create a new Observer with the specified callback
  5471. * @param callback the callback that will be executed for that Observer
  5472. * @param mask the mask used to filter observers
  5473. * @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.
  5474. * @param scope optional scope for the callback to be called from
  5475. */
  5476. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5477. if (mask === void 0) { mask = -1; }
  5478. if (insertFirst === void 0) { insertFirst = false; }
  5479. if (scope === void 0) { scope = null; }
  5480. if (!callback) {
  5481. return null;
  5482. }
  5483. var observer = new Observer(callback, mask, scope);
  5484. if (insertFirst) {
  5485. this._observers.unshift(observer);
  5486. }
  5487. else {
  5488. this._observers.push(observer);
  5489. }
  5490. if (this._onObserverAdded) {
  5491. this._onObserverAdded(observer);
  5492. }
  5493. return observer;
  5494. };
  5495. /**
  5496. * Remove an Observer from the Observable object
  5497. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5498. */
  5499. Observable.prototype.remove = function (observer) {
  5500. if (!observer) {
  5501. return false;
  5502. }
  5503. var index = this._observers.indexOf(observer);
  5504. if (index !== -1) {
  5505. this._observers.splice(index, 1);
  5506. return true;
  5507. }
  5508. return false;
  5509. };
  5510. /**
  5511. * Remove a callback from the Observable object
  5512. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5513. */
  5514. Observable.prototype.removeCallback = function (callback) {
  5515. for (var index = 0; index < this._observers.length; index++) {
  5516. if (this._observers[index].callback === callback) {
  5517. this._observers.splice(index, 1);
  5518. return true;
  5519. }
  5520. }
  5521. return false;
  5522. };
  5523. /**
  5524. * Notify all Observers by calling their respective callback with the given data
  5525. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5526. * @param eventData
  5527. * @param mask
  5528. */
  5529. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5530. if (mask === void 0) { mask = -1; }
  5531. var state = this._eventState;
  5532. state.mask = mask;
  5533. state.target = target;
  5534. state.currentTarget = currentTarget;
  5535. state.skipNextObservers = false;
  5536. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5537. var obs = _a[_i];
  5538. if (obs.mask & mask) {
  5539. if (obs.scope) {
  5540. obs.callback.apply(obs.scope, [eventData, state]);
  5541. }
  5542. else {
  5543. obs.callback(eventData, state);
  5544. }
  5545. }
  5546. if (state.skipNextObservers) {
  5547. return false;
  5548. }
  5549. }
  5550. return true;
  5551. };
  5552. /**
  5553. * Notify a specific observer
  5554. * @param eventData
  5555. * @param mask
  5556. */
  5557. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5558. if (mask === void 0) { mask = -1; }
  5559. var state = this._eventState;
  5560. state.mask = mask;
  5561. state.skipNextObservers = false;
  5562. observer.callback(eventData, state);
  5563. };
  5564. /**
  5565. * return true is the Observable has at least one Observer registered
  5566. */
  5567. Observable.prototype.hasObservers = function () {
  5568. return this._observers.length > 0;
  5569. };
  5570. /**
  5571. * Clear the list of observers
  5572. */
  5573. Observable.prototype.clear = function () {
  5574. this._observers = new Array();
  5575. this._onObserverAdded = null;
  5576. };
  5577. /**
  5578. * Clone the current observable
  5579. */
  5580. Observable.prototype.clone = function () {
  5581. var result = new Observable();
  5582. result._observers = this._observers.slice(0);
  5583. return result;
  5584. };
  5585. /**
  5586. * Does this observable handles observer registered with a given mask
  5587. * @param {number} trigger - the mask to be tested
  5588. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5589. **/
  5590. Observable.prototype.hasSpecificMask = function (mask) {
  5591. if (mask === void 0) { mask = -1; }
  5592. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5593. var obs = _a[_i];
  5594. if (obs.mask & mask || obs.mask === mask) {
  5595. return true;
  5596. }
  5597. }
  5598. return false;
  5599. };
  5600. return Observable;
  5601. }());
  5602. BABYLON.Observable = Observable;
  5603. })(BABYLON || (BABYLON = {}));
  5604. //# sourceMappingURL=babylon.observable.js.map
  5605. var BABYLON;
  5606. (function (BABYLON) {
  5607. var SmartArray = /** @class */ (function () {
  5608. function SmartArray(capacity) {
  5609. this.length = 0;
  5610. this._duplicateId = 0;
  5611. this.data = new Array(capacity);
  5612. this._id = SmartArray._GlobalId++;
  5613. }
  5614. SmartArray.prototype.push = function (value) {
  5615. this.data[this.length++] = value;
  5616. if (this.length > this.data.length) {
  5617. this.data.length *= 2;
  5618. }
  5619. if (!value.__smartArrayFlags) {
  5620. value.__smartArrayFlags = {};
  5621. }
  5622. value.__smartArrayFlags[this._id] = this._duplicateId;
  5623. };
  5624. SmartArray.prototype.forEach = function (func) {
  5625. for (var index = 0; index < this.length; index++) {
  5626. func(this.data[index]);
  5627. }
  5628. };
  5629. SmartArray.prototype.pushNoDuplicate = function (value) {
  5630. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5631. return false;
  5632. }
  5633. this.push(value);
  5634. return true;
  5635. };
  5636. SmartArray.prototype.sort = function (compareFn) {
  5637. this.data.sort(compareFn);
  5638. };
  5639. SmartArray.prototype.reset = function () {
  5640. this.length = 0;
  5641. this._duplicateId++;
  5642. };
  5643. SmartArray.prototype.dispose = function () {
  5644. this.reset();
  5645. if (this.data) {
  5646. this.data.length = 0;
  5647. this.data = [];
  5648. }
  5649. };
  5650. SmartArray.prototype.concat = function (array) {
  5651. if (array.length === 0) {
  5652. return;
  5653. }
  5654. if (this.length + array.length > this.data.length) {
  5655. this.data.length = (this.length + array.length) * 2;
  5656. }
  5657. for (var index = 0; index < array.length; index++) {
  5658. this.data[this.length++] = (array.data || array)[index];
  5659. }
  5660. };
  5661. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5662. if (array.length === 0) {
  5663. return;
  5664. }
  5665. if (this.length + array.length > this.data.length) {
  5666. this.data.length = (this.length + array.length) * 2;
  5667. }
  5668. for (var index = 0; index < array.length; index++) {
  5669. var item = (array.data || array)[index];
  5670. this.pushNoDuplicate(item);
  5671. }
  5672. };
  5673. SmartArray.prototype.indexOf = function (value) {
  5674. var position = this.data.indexOf(value);
  5675. if (position >= this.length) {
  5676. return -1;
  5677. }
  5678. return position;
  5679. };
  5680. SmartArray.prototype.contains = function (value) {
  5681. return this.data.indexOf(value) !== -1;
  5682. };
  5683. // Statics
  5684. SmartArray._GlobalId = 0;
  5685. return SmartArray;
  5686. }());
  5687. BABYLON.SmartArray = SmartArray;
  5688. })(BABYLON || (BABYLON = {}));
  5689. //# sourceMappingURL=babylon.smartArray.js.map
  5690. var BABYLON;
  5691. (function (BABYLON) {
  5692. // Screenshots
  5693. var screenshotCanvas;
  5694. var cloneValue = function (source, destinationObject) {
  5695. if (!source)
  5696. return null;
  5697. if (source instanceof BABYLON.Mesh) {
  5698. return null;
  5699. }
  5700. if (source instanceof BABYLON.SubMesh) {
  5701. return source.clone(destinationObject);
  5702. }
  5703. else if (source.clone) {
  5704. return source.clone();
  5705. }
  5706. return null;
  5707. };
  5708. var Tools = /** @class */ (function () {
  5709. function Tools() {
  5710. }
  5711. ;
  5712. /**
  5713. * Interpolates between a and b via alpha
  5714. * @param a The lower value (returned when alpha = 0)
  5715. * @param b The upper value (returned when alpha = 1)
  5716. * @param alpha The interpolation-factor
  5717. * @return The mixed value
  5718. */
  5719. Tools.Mix = function (a, b, alpha) {
  5720. return a * (1 - alpha) + b * alpha;
  5721. };
  5722. Tools.Instantiate = function (className) {
  5723. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5724. return Tools.RegisteredExternalClasses[className];
  5725. }
  5726. var arr = className.split(".");
  5727. var fn = (window || this);
  5728. for (var i = 0, len = arr.length; i < len; i++) {
  5729. fn = fn[arr[i]];
  5730. }
  5731. if (typeof fn !== "function") {
  5732. return null;
  5733. }
  5734. return fn;
  5735. };
  5736. Tools.SetImmediate = function (action) {
  5737. if (window.setImmediate) {
  5738. window.setImmediate(action);
  5739. }
  5740. else {
  5741. setTimeout(action, 1);
  5742. }
  5743. };
  5744. Tools.IsExponentOfTwo = function (value) {
  5745. var count = 1;
  5746. do {
  5747. count *= 2;
  5748. } while (count < value);
  5749. return count === value;
  5750. };
  5751. /**
  5752. * Find the next highest power of two.
  5753. * @param x Number to start search from.
  5754. * @return Next highest power of two.
  5755. */
  5756. Tools.CeilingPOT = function (x) {
  5757. x--;
  5758. x |= x >> 1;
  5759. x |= x >> 2;
  5760. x |= x >> 4;
  5761. x |= x >> 8;
  5762. x |= x >> 16;
  5763. x++;
  5764. return x;
  5765. };
  5766. /**
  5767. * Find the next lowest power of two.
  5768. * @param x Number to start search from.
  5769. * @return Next lowest power of two.
  5770. */
  5771. Tools.FloorPOT = function (x) {
  5772. x = x | (x >> 1);
  5773. x = x | (x >> 2);
  5774. x = x | (x >> 4);
  5775. x = x | (x >> 8);
  5776. x = x | (x >> 16);
  5777. return x - (x >> 1);
  5778. };
  5779. /**
  5780. * Find the nearest power of two.
  5781. * @param x Number to start search from.
  5782. * @return Next nearest power of two.
  5783. */
  5784. Tools.NearestPOT = function (x) {
  5785. var c = Tools.CeilingPOT(x);
  5786. var f = Tools.FloorPOT(x);
  5787. return (c - x) > (x - f) ? f : c;
  5788. };
  5789. Tools.GetExponentOfTwo = function (value, max, mode) {
  5790. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5791. var pot;
  5792. switch (mode) {
  5793. case BABYLON.Engine.SCALEMODE_FLOOR:
  5794. pot = Tools.FloorPOT(value);
  5795. break;
  5796. case BABYLON.Engine.SCALEMODE_NEAREST:
  5797. pot = Tools.NearestPOT(value);
  5798. break;
  5799. case BABYLON.Engine.SCALEMODE_CEILING:
  5800. default:
  5801. pot = Tools.CeilingPOT(value);
  5802. break;
  5803. }
  5804. return Math.min(pot, max);
  5805. };
  5806. Tools.GetFilename = function (path) {
  5807. var index = path.lastIndexOf("/");
  5808. if (index < 0)
  5809. return path;
  5810. return path.substring(index + 1);
  5811. };
  5812. Tools.GetDOMTextContent = function (element) {
  5813. var result = "";
  5814. var child = element.firstChild;
  5815. while (child) {
  5816. if (child.nodeType === 3) {
  5817. result += child.textContent;
  5818. }
  5819. child = child.nextSibling;
  5820. }
  5821. return result;
  5822. };
  5823. Tools.ToDegrees = function (angle) {
  5824. return angle * 180 / Math.PI;
  5825. };
  5826. Tools.ToRadians = function (angle) {
  5827. return angle * Math.PI / 180;
  5828. };
  5829. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5830. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5831. var output = "";
  5832. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5833. var i = 0;
  5834. var bytes = new Uint8Array(buffer);
  5835. while (i < bytes.length) {
  5836. chr1 = bytes[i++];
  5837. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5838. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5839. enc1 = chr1 >> 2;
  5840. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5841. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5842. enc4 = chr3 & 63;
  5843. if (isNaN(chr2)) {
  5844. enc3 = enc4 = 64;
  5845. }
  5846. else if (isNaN(chr3)) {
  5847. enc4 = 64;
  5848. }
  5849. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5850. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5851. }
  5852. return "data:image/png;base64," + output;
  5853. };
  5854. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5855. if (bias === void 0) { bias = null; }
  5856. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5857. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5858. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5859. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5860. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5861. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5862. }
  5863. if (bias) {
  5864. minimum.x -= minimum.x * bias.x + bias.y;
  5865. minimum.y -= minimum.y * bias.x + bias.y;
  5866. minimum.z -= minimum.z * bias.x + bias.y;
  5867. maximum.x += maximum.x * bias.x + bias.y;
  5868. maximum.y += maximum.y * bias.x + bias.y;
  5869. maximum.z += maximum.z * bias.x + bias.y;
  5870. }
  5871. return {
  5872. minimum: minimum,
  5873. maximum: maximum
  5874. };
  5875. };
  5876. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5877. if (bias === void 0) { bias = null; }
  5878. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5879. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5880. if (!stride) {
  5881. stride = 3;
  5882. }
  5883. for (var index = start; index < start + count; index++) {
  5884. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5885. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5886. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5887. }
  5888. if (bias) {
  5889. minimum.x -= minimum.x * bias.x + bias.y;
  5890. minimum.y -= minimum.y * bias.x + bias.y;
  5891. minimum.z -= minimum.z * bias.x + bias.y;
  5892. maximum.x += maximum.x * bias.x + bias.y;
  5893. maximum.y += maximum.y * bias.x + bias.y;
  5894. maximum.z += maximum.z * bias.x + bias.y;
  5895. }
  5896. return {
  5897. minimum: minimum,
  5898. maximum: maximum
  5899. };
  5900. };
  5901. Tools.Vector2ArrayFeeder = function (array) {
  5902. return function (index) {
  5903. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5904. var length = isFloatArray ? array.length / 2 : array.length;
  5905. if (index >= length) {
  5906. return null;
  5907. }
  5908. if (isFloatArray) {
  5909. var fa = array;
  5910. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5911. }
  5912. var a = array;
  5913. return a[index];
  5914. };
  5915. };
  5916. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5917. if (bias === void 0) { bias = null; }
  5918. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5919. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5920. var i = 0;
  5921. var cur = feeder(i++);
  5922. while (cur) {
  5923. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5924. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5925. cur = feeder(i++);
  5926. }
  5927. if (bias) {
  5928. minimum.x -= minimum.x * bias.x + bias.y;
  5929. minimum.y -= minimum.y * bias.x + bias.y;
  5930. maximum.x += maximum.x * bias.x + bias.y;
  5931. maximum.y += maximum.y * bias.x + bias.y;
  5932. }
  5933. return {
  5934. minimum: minimum,
  5935. maximum: maximum
  5936. };
  5937. };
  5938. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5939. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5940. return null;
  5941. return Array.isArray(obj) ? obj : [obj];
  5942. };
  5943. // Misc.
  5944. Tools.GetPointerPrefix = function () {
  5945. var eventPrefix = "pointer";
  5946. // Check if pointer events are supported
  5947. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5948. eventPrefix = "mouse";
  5949. }
  5950. return eventPrefix;
  5951. };
  5952. /**
  5953. * @param func - the function to be called
  5954. * @param requester - the object that will request the next frame. Falls back to window.
  5955. */
  5956. Tools.QueueNewFrame = function (func, requester) {
  5957. if (!Tools.IsWindowObjectExist()) {
  5958. return setTimeout(func, 16);
  5959. }
  5960. if (!requester) {
  5961. requester = window;
  5962. }
  5963. if (requester.requestAnimationFrame) {
  5964. return requester.requestAnimationFrame(func);
  5965. }
  5966. else if (requester.msRequestAnimationFrame) {
  5967. return requester.msRequestAnimationFrame(func);
  5968. }
  5969. else if (requester.webkitRequestAnimationFrame) {
  5970. return requester.webkitRequestAnimationFrame(func);
  5971. }
  5972. else if (requester.mozRequestAnimationFrame) {
  5973. return requester.mozRequestAnimationFrame(func);
  5974. }
  5975. else if (requester.oRequestAnimationFrame) {
  5976. return requester.oRequestAnimationFrame(func);
  5977. }
  5978. else {
  5979. return window.setTimeout(func, 16);
  5980. }
  5981. };
  5982. Tools.RequestFullscreen = function (element) {
  5983. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5984. if (!requestFunction)
  5985. return;
  5986. requestFunction.call(element);
  5987. };
  5988. Tools.ExitFullscreen = function () {
  5989. if (document.exitFullscreen) {
  5990. document.exitFullscreen();
  5991. }
  5992. else if (document.mozCancelFullScreen) {
  5993. document.mozCancelFullScreen();
  5994. }
  5995. else if (document.webkitCancelFullScreen) {
  5996. document.webkitCancelFullScreen();
  5997. }
  5998. else if (document.msCancelFullScreen) {
  5999. document.msCancelFullScreen();
  6000. }
  6001. };
  6002. Tools.SetCorsBehavior = function (url, img) {
  6003. if (Tools.CorsBehavior) {
  6004. switch (typeof (Tools.CorsBehavior)) {
  6005. case "function":
  6006. var result = Tools.CorsBehavior(url);
  6007. if (result) {
  6008. img.crossOrigin = result;
  6009. }
  6010. break;
  6011. case "string":
  6012. default:
  6013. img.crossOrigin = Tools.CorsBehavior;
  6014. break;
  6015. }
  6016. }
  6017. };
  6018. // External files
  6019. Tools.CleanUrl = function (url) {
  6020. url = url.replace(/#/mg, "%23");
  6021. return url;
  6022. };
  6023. Tools.LoadImage = function (url, onLoad, onError, database) {
  6024. if (url instanceof ArrayBuffer) {
  6025. url = Tools.EncodeArrayBufferTobase64(url);
  6026. }
  6027. url = Tools.CleanUrl(url);
  6028. url = Tools.PreprocessUrl(url);
  6029. var img = new Image();
  6030. if (url.substr(0, 5) !== "data:") {
  6031. Tools.SetCorsBehavior(url, img);
  6032. }
  6033. img.onload = function () {
  6034. onLoad(img);
  6035. };
  6036. img.onerror = function (err) {
  6037. Tools.Error("Error while trying to load image: " + url);
  6038. if (Tools.UseFallbackTexture) {
  6039. img.src = Tools.fallbackTexture;
  6040. onLoad(img);
  6041. }
  6042. else {
  6043. onError("Error while trying to load image: " + url, err);
  6044. }
  6045. };
  6046. var noIndexedDB = function () {
  6047. img.src = url;
  6048. };
  6049. var loadFromIndexedDB = function () {
  6050. if (database) {
  6051. database.loadImageFromDB(url, img);
  6052. }
  6053. };
  6054. //ANY database to do!
  6055. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6056. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6057. }
  6058. else {
  6059. if (url.indexOf("file:") !== 0) {
  6060. noIndexedDB();
  6061. }
  6062. else {
  6063. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6064. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6065. try {
  6066. var blobURL;
  6067. try {
  6068. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6069. }
  6070. catch (ex) {
  6071. // Chrome doesn't support oneTimeOnly parameter
  6072. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6073. }
  6074. img.src = blobURL;
  6075. }
  6076. catch (e) {
  6077. img.src = "";
  6078. }
  6079. }
  6080. else {
  6081. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6082. img.src = Tools.fallbackTexture;
  6083. }
  6084. }
  6085. }
  6086. return img;
  6087. };
  6088. //ANY
  6089. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6090. url = Tools.CleanUrl(url);
  6091. url = Tools.PreprocessUrl(url);
  6092. var request = null;
  6093. var noIndexedDB = function () {
  6094. request = new XMLHttpRequest();
  6095. var loadUrl = Tools.BaseUrl + url;
  6096. request.open('GET', loadUrl, true);
  6097. if (useArrayBuffer) {
  6098. request.responseType = "arraybuffer";
  6099. }
  6100. if (progressCallBack) {
  6101. request.onprogress = progressCallBack;
  6102. }
  6103. request.onreadystatechange = function () {
  6104. var req = request;
  6105. // In case of undefined state in some browsers.
  6106. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6107. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6108. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6109. callback(!useArrayBuffer ? req.responseText : req.response);
  6110. }
  6111. else {
  6112. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6113. if (onError) {
  6114. onError(req, e);
  6115. }
  6116. else {
  6117. throw e;
  6118. }
  6119. }
  6120. }
  6121. };
  6122. request.send(null);
  6123. };
  6124. var loadFromIndexedDB = function () {
  6125. if (database) {
  6126. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6127. }
  6128. };
  6129. if (url.indexOf("file:") !== -1) {
  6130. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6131. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6132. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6133. }
  6134. else {
  6135. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6136. if (onError) {
  6137. var e = new Error(errorMessage);
  6138. onError(undefined, e);
  6139. }
  6140. else {
  6141. Tools.Error(errorMessage);
  6142. }
  6143. }
  6144. }
  6145. else {
  6146. // Caching all files
  6147. if (database && database.enableSceneOffline) {
  6148. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6149. }
  6150. else {
  6151. noIndexedDB();
  6152. }
  6153. }
  6154. return request;
  6155. };
  6156. /**
  6157. * Load a script (identified by an url). When the url returns, the
  6158. * content of this file is added into a new script element, attached to the DOM (body element)
  6159. */
  6160. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6161. var head = document.getElementsByTagName('head')[0];
  6162. var script = document.createElement('script');
  6163. script.type = 'text/javascript';
  6164. script.src = scriptUrl;
  6165. script.onload = function () {
  6166. if (onSuccess) {
  6167. onSuccess();
  6168. }
  6169. };
  6170. script.onerror = function (e) {
  6171. if (onError) {
  6172. onError("Unable to load script", e);
  6173. }
  6174. };
  6175. head.appendChild(script);
  6176. };
  6177. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6178. var reader = new FileReader();
  6179. reader.onload = function (e) {
  6180. //target doesn't have result from ts 1.3
  6181. callback(e.target['result']);
  6182. };
  6183. reader.onprogress = progressCallback;
  6184. reader.readAsDataURL(fileToLoad);
  6185. };
  6186. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6187. var reader = new FileReader();
  6188. reader.onerror = function (e) {
  6189. Tools.Log("Error while reading file: " + fileToLoad.name);
  6190. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6191. };
  6192. reader.onload = function (e) {
  6193. //target doesn't have result from ts 1.3
  6194. callback(e.target['result']);
  6195. };
  6196. if (progressCallBack) {
  6197. reader.onprogress = progressCallBack;
  6198. }
  6199. if (!useArrayBuffer) {
  6200. // Asynchronous read
  6201. reader.readAsText(fileToLoad);
  6202. }
  6203. else {
  6204. reader.readAsArrayBuffer(fileToLoad);
  6205. }
  6206. };
  6207. //returns a downloadable url to a file content.
  6208. Tools.FileAsURL = function (content) {
  6209. var fileBlob = new Blob([content]);
  6210. var url = window.URL || window.webkitURL;
  6211. var link = url.createObjectURL(fileBlob);
  6212. return link;
  6213. };
  6214. // Misc.
  6215. Tools.Format = function (value, decimals) {
  6216. if (decimals === void 0) { decimals = 2; }
  6217. return value.toFixed(decimals);
  6218. };
  6219. Tools.CheckExtends = function (v, min, max) {
  6220. if (v.x < min.x)
  6221. min.x = v.x;
  6222. if (v.y < min.y)
  6223. min.y = v.y;
  6224. if (v.z < min.z)
  6225. min.z = v.z;
  6226. if (v.x > max.x)
  6227. max.x = v.x;
  6228. if (v.y > max.y)
  6229. max.y = v.y;
  6230. if (v.z > max.z)
  6231. max.z = v.z;
  6232. };
  6233. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6234. for (var prop in source) {
  6235. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6236. continue;
  6237. }
  6238. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6239. continue;
  6240. }
  6241. var sourceValue = source[prop];
  6242. var typeOfSourceValue = typeof sourceValue;
  6243. if (typeOfSourceValue === "function") {
  6244. continue;
  6245. }
  6246. if (typeOfSourceValue === "object") {
  6247. if (sourceValue instanceof Array) {
  6248. destination[prop] = [];
  6249. if (sourceValue.length > 0) {
  6250. if (typeof sourceValue[0] == "object") {
  6251. for (var index = 0; index < sourceValue.length; index++) {
  6252. var clonedValue = cloneValue(sourceValue[index], destination);
  6253. if (destination[prop].indexOf(clonedValue) === -1) {
  6254. destination[prop].push(clonedValue);
  6255. }
  6256. }
  6257. }
  6258. else {
  6259. destination[prop] = sourceValue.slice(0);
  6260. }
  6261. }
  6262. }
  6263. else {
  6264. destination[prop] = cloneValue(sourceValue, destination);
  6265. }
  6266. }
  6267. else {
  6268. destination[prop] = sourceValue;
  6269. }
  6270. }
  6271. };
  6272. Tools.IsEmpty = function (obj) {
  6273. for (var i in obj) {
  6274. if (obj.hasOwnProperty(i)) {
  6275. return false;
  6276. }
  6277. }
  6278. return true;
  6279. };
  6280. Tools.RegisterTopRootEvents = function (events) {
  6281. for (var index = 0; index < events.length; index++) {
  6282. var event = events[index];
  6283. window.addEventListener(event.name, event.handler, false);
  6284. try {
  6285. if (window.parent) {
  6286. window.parent.addEventListener(event.name, event.handler, false);
  6287. }
  6288. }
  6289. catch (e) {
  6290. // Silently fails...
  6291. }
  6292. }
  6293. };
  6294. Tools.UnregisterTopRootEvents = function (events) {
  6295. for (var index = 0; index < events.length; index++) {
  6296. var event = events[index];
  6297. window.removeEventListener(event.name, event.handler);
  6298. try {
  6299. if (window.parent) {
  6300. window.parent.removeEventListener(event.name, event.handler);
  6301. }
  6302. }
  6303. catch (e) {
  6304. // Silently fails...
  6305. }
  6306. }
  6307. };
  6308. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6309. if (mimeType === void 0) { mimeType = "image/png"; }
  6310. // Read the contents of the framebuffer
  6311. var numberOfChannelsByLine = width * 4;
  6312. var halfHeight = height / 2;
  6313. //Reading datas from WebGL
  6314. var data = engine.readPixels(0, 0, width, height);
  6315. //To flip image on Y axis.
  6316. for (var i = 0; i < halfHeight; i++) {
  6317. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6318. var currentCell = j + i * numberOfChannelsByLine;
  6319. var targetLine = height - i - 1;
  6320. var targetCell = j + targetLine * numberOfChannelsByLine;
  6321. var temp = data[currentCell];
  6322. data[currentCell] = data[targetCell];
  6323. data[targetCell] = temp;
  6324. }
  6325. }
  6326. // Create a 2D canvas to store the result
  6327. if (!screenshotCanvas) {
  6328. screenshotCanvas = document.createElement('canvas');
  6329. }
  6330. screenshotCanvas.width = width;
  6331. screenshotCanvas.height = height;
  6332. var context = screenshotCanvas.getContext('2d');
  6333. if (context) {
  6334. // Copy the pixels to a 2D canvas
  6335. var imageData = context.createImageData(width, height);
  6336. var castData = (imageData.data);
  6337. castData.set(data);
  6338. context.putImageData(imageData, 0, 0);
  6339. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6340. }
  6341. };
  6342. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6343. if (mimeType === void 0) { mimeType = "image/png"; }
  6344. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6345. if (successCallback) {
  6346. successCallback(base64Image);
  6347. }
  6348. else {
  6349. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6350. if (("download" in document.createElement("a"))) {
  6351. var a = window.document.createElement("a");
  6352. a.href = base64Image;
  6353. var date = new Date();
  6354. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6355. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6356. window.document.body.appendChild(a);
  6357. a.addEventListener("click", function () {
  6358. if (a.parentElement) {
  6359. a.parentElement.removeChild(a);
  6360. }
  6361. });
  6362. a.click();
  6363. //Or opening a new tab with the image if it is not possible to automatically start download.
  6364. }
  6365. else {
  6366. var newWindow = window.open("");
  6367. var img = newWindow.document.createElement("img");
  6368. img.src = base64Image;
  6369. newWindow.document.body.appendChild(img);
  6370. }
  6371. }
  6372. };
  6373. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6374. if (mimeType === void 0) { mimeType = "image/png"; }
  6375. var width;
  6376. var height;
  6377. // If a precision value is specified
  6378. if (size.precision) {
  6379. width = Math.round(engine.getRenderWidth() * size.precision);
  6380. height = Math.round(width / engine.getAspectRatio(camera));
  6381. }
  6382. else if (size.width && size.height) {
  6383. width = size.width;
  6384. height = size.height;
  6385. }
  6386. else if (size.width && !size.height) {
  6387. width = size.width;
  6388. height = Math.round(width / engine.getAspectRatio(camera));
  6389. }
  6390. else if (size.height && !size.width) {
  6391. height = size.height;
  6392. width = Math.round(height * engine.getAspectRatio(camera));
  6393. }
  6394. else if (!isNaN(size)) {
  6395. height = size;
  6396. width = size;
  6397. }
  6398. else {
  6399. Tools.Error("Invalid 'size' parameter !");
  6400. return;
  6401. }
  6402. if (!screenshotCanvas) {
  6403. screenshotCanvas = document.createElement('canvas');
  6404. }
  6405. screenshotCanvas.width = width;
  6406. screenshotCanvas.height = height;
  6407. var renderContext = screenshotCanvas.getContext("2d");
  6408. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6409. var newWidth = width;
  6410. var newHeight = newWidth / ratio;
  6411. if (newHeight > height) {
  6412. newHeight = height;
  6413. newWidth = newHeight * ratio;
  6414. }
  6415. var offsetX = Math.max(0, width - newWidth) / 2;
  6416. var offsetY = Math.max(0, height - newHeight) / 2;
  6417. var renderingCanvas = engine.getRenderingCanvas();
  6418. if (renderContext && renderingCanvas) {
  6419. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6420. }
  6421. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6422. };
  6423. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6424. if (mimeType === void 0) { mimeType = "image/png"; }
  6425. if (samples === void 0) { samples = 1; }
  6426. var width;
  6427. var height;
  6428. //If a precision value is specified
  6429. if (size.precision) {
  6430. width = Math.round(engine.getRenderWidth() * size.precision);
  6431. height = Math.round(width / engine.getAspectRatio(camera));
  6432. size = { width: width, height: height };
  6433. }
  6434. else if (size.width && size.height) {
  6435. width = size.width;
  6436. height = size.height;
  6437. }
  6438. else if (size.width && !size.height) {
  6439. width = size.width;
  6440. height = Math.round(width / engine.getAspectRatio(camera));
  6441. size = { width: width, height: height };
  6442. }
  6443. else if (size.height && !size.width) {
  6444. height = size.height;
  6445. width = Math.round(height * engine.getAspectRatio(camera));
  6446. size = { width: width, height: height };
  6447. }
  6448. else if (!isNaN(size)) {
  6449. height = size;
  6450. width = size;
  6451. }
  6452. else {
  6453. Tools.Error("Invalid 'size' parameter !");
  6454. return;
  6455. }
  6456. var scene = camera.getScene();
  6457. var previousCamera = null;
  6458. if (scene.activeCamera !== camera) {
  6459. previousCamera = scene.activeCamera;
  6460. scene.activeCamera = camera;
  6461. }
  6462. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6463. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6464. texture.renderList = null;
  6465. texture.samples = samples;
  6466. texture.onAfterRenderObservable.add(function () {
  6467. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6468. });
  6469. scene.incrementRenderId();
  6470. scene.resetCachedMaterial();
  6471. texture.render(true);
  6472. texture.dispose();
  6473. if (previousCamera) {
  6474. scene.activeCamera = previousCamera;
  6475. }
  6476. camera.getProjectionMatrix(true); // Force cache refresh;
  6477. };
  6478. // XHR response validator for local file scenario
  6479. Tools.ValidateXHRData = function (xhr, dataType) {
  6480. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6481. if (dataType === void 0) { dataType = 7; }
  6482. try {
  6483. if (dataType & 1) {
  6484. if (xhr.responseText && xhr.responseText.length > 0) {
  6485. return true;
  6486. }
  6487. else if (dataType === 1) {
  6488. return false;
  6489. }
  6490. }
  6491. if (dataType & 2) {
  6492. // Check header width and height since there is no "TGA" magic number
  6493. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6494. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6495. return true;
  6496. }
  6497. else if (dataType === 2) {
  6498. return false;
  6499. }
  6500. }
  6501. if (dataType & 4) {
  6502. // Check for the "DDS" magic number
  6503. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6504. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6505. return true;
  6506. }
  6507. else {
  6508. return false;
  6509. }
  6510. }
  6511. }
  6512. catch (e) {
  6513. // Global protection
  6514. }
  6515. return false;
  6516. };
  6517. /**
  6518. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6519. * Be aware Math.random() could cause collisions, but:
  6520. * "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"
  6521. */
  6522. Tools.RandomId = function () {
  6523. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6524. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6525. return v.toString(16);
  6526. });
  6527. };
  6528. Object.defineProperty(Tools, "NoneLogLevel", {
  6529. get: function () {
  6530. return Tools._NoneLogLevel;
  6531. },
  6532. enumerable: true,
  6533. configurable: true
  6534. });
  6535. Object.defineProperty(Tools, "MessageLogLevel", {
  6536. get: function () {
  6537. return Tools._MessageLogLevel;
  6538. },
  6539. enumerable: true,
  6540. configurable: true
  6541. });
  6542. Object.defineProperty(Tools, "WarningLogLevel", {
  6543. get: function () {
  6544. return Tools._WarningLogLevel;
  6545. },
  6546. enumerable: true,
  6547. configurable: true
  6548. });
  6549. Object.defineProperty(Tools, "ErrorLogLevel", {
  6550. get: function () {
  6551. return Tools._ErrorLogLevel;
  6552. },
  6553. enumerable: true,
  6554. configurable: true
  6555. });
  6556. Object.defineProperty(Tools, "AllLogLevel", {
  6557. get: function () {
  6558. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6559. },
  6560. enumerable: true,
  6561. configurable: true
  6562. });
  6563. Tools._AddLogEntry = function (entry) {
  6564. Tools._LogCache = entry + Tools._LogCache;
  6565. if (Tools.OnNewCacheEntry) {
  6566. Tools.OnNewCacheEntry(entry);
  6567. }
  6568. };
  6569. Tools._FormatMessage = function (message) {
  6570. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6571. var date = new Date();
  6572. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6573. };
  6574. Tools._LogDisabled = function (message) {
  6575. // nothing to do
  6576. };
  6577. Tools._LogEnabled = function (message) {
  6578. var formattedMessage = Tools._FormatMessage(message);
  6579. console.log("BJS - " + formattedMessage);
  6580. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6581. Tools._AddLogEntry(entry);
  6582. };
  6583. Tools._WarnDisabled = function (message) {
  6584. // nothing to do
  6585. };
  6586. Tools._WarnEnabled = function (message) {
  6587. var formattedMessage = Tools._FormatMessage(message);
  6588. console.warn("BJS - " + formattedMessage);
  6589. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6590. Tools._AddLogEntry(entry);
  6591. };
  6592. Tools._ErrorDisabled = function (message) {
  6593. // nothing to do
  6594. };
  6595. Tools._ErrorEnabled = function (message) {
  6596. Tools.errorsCount++;
  6597. var formattedMessage = Tools._FormatMessage(message);
  6598. console.error("BJS - " + formattedMessage);
  6599. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6600. Tools._AddLogEntry(entry);
  6601. };
  6602. Object.defineProperty(Tools, "LogCache", {
  6603. get: function () {
  6604. return Tools._LogCache;
  6605. },
  6606. enumerable: true,
  6607. configurable: true
  6608. });
  6609. Tools.ClearLogCache = function () {
  6610. Tools._LogCache = "";
  6611. Tools.errorsCount = 0;
  6612. };
  6613. Object.defineProperty(Tools, "LogLevels", {
  6614. set: function (level) {
  6615. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6616. Tools.Log = Tools._LogEnabled;
  6617. }
  6618. else {
  6619. Tools.Log = Tools._LogDisabled;
  6620. }
  6621. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6622. Tools.Warn = Tools._WarnEnabled;
  6623. }
  6624. else {
  6625. Tools.Warn = Tools._WarnDisabled;
  6626. }
  6627. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6628. Tools.Error = Tools._ErrorEnabled;
  6629. }
  6630. else {
  6631. Tools.Error = Tools._ErrorDisabled;
  6632. }
  6633. },
  6634. enumerable: true,
  6635. configurable: true
  6636. });
  6637. Tools.IsWindowObjectExist = function () {
  6638. return (typeof window) !== "undefined";
  6639. };
  6640. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6641. get: function () {
  6642. return Tools._PerformanceNoneLogLevel;
  6643. },
  6644. enumerable: true,
  6645. configurable: true
  6646. });
  6647. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6648. get: function () {
  6649. return Tools._PerformanceUserMarkLogLevel;
  6650. },
  6651. enumerable: true,
  6652. configurable: true
  6653. });
  6654. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6655. get: function () {
  6656. return Tools._PerformanceConsoleLogLevel;
  6657. },
  6658. enumerable: true,
  6659. configurable: true
  6660. });
  6661. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6662. set: function (level) {
  6663. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6664. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6665. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6666. return;
  6667. }
  6668. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6669. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6670. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6671. return;
  6672. }
  6673. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6674. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6675. },
  6676. enumerable: true,
  6677. configurable: true
  6678. });
  6679. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6680. };
  6681. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6682. };
  6683. Tools._StartUserMark = function (counterName, condition) {
  6684. if (condition === void 0) { condition = true; }
  6685. if (!Tools._performance) {
  6686. if (!Tools.IsWindowObjectExist()) {
  6687. return;
  6688. }
  6689. Tools._performance = window.performance;
  6690. }
  6691. if (!condition || !Tools._performance.mark) {
  6692. return;
  6693. }
  6694. Tools._performance.mark(counterName + "-Begin");
  6695. };
  6696. Tools._EndUserMark = function (counterName, condition) {
  6697. if (condition === void 0) { condition = true; }
  6698. if (!condition || !Tools._performance.mark) {
  6699. return;
  6700. }
  6701. Tools._performance.mark(counterName + "-End");
  6702. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6703. };
  6704. Tools._StartPerformanceConsole = function (counterName, condition) {
  6705. if (condition === void 0) { condition = true; }
  6706. if (!condition) {
  6707. return;
  6708. }
  6709. Tools._StartUserMark(counterName, condition);
  6710. if (console.time) {
  6711. console.time(counterName);
  6712. }
  6713. };
  6714. Tools._EndPerformanceConsole = function (counterName, condition) {
  6715. if (condition === void 0) { condition = true; }
  6716. if (!condition) {
  6717. return;
  6718. }
  6719. Tools._EndUserMark(counterName, condition);
  6720. if (console.time) {
  6721. console.timeEnd(counterName);
  6722. }
  6723. };
  6724. Object.defineProperty(Tools, "Now", {
  6725. get: function () {
  6726. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6727. return window.performance.now();
  6728. }
  6729. return new Date().getTime();
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. /**
  6735. * This method will return the name of the class used to create the instance of the given object.
  6736. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6737. * @param object the object to get the class name from
  6738. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6739. */
  6740. Tools.GetClassName = function (object, isType) {
  6741. if (isType === void 0) { isType = false; }
  6742. var name = null;
  6743. if (!isType && object.getClassName) {
  6744. name = object.getClassName();
  6745. }
  6746. else {
  6747. if (object instanceof Object) {
  6748. var classObj = isType ? object : Object.getPrototypeOf(object);
  6749. name = classObj.constructor["__bjsclassName__"];
  6750. }
  6751. if (!name) {
  6752. name = typeof object;
  6753. }
  6754. }
  6755. return name;
  6756. };
  6757. Tools.First = function (array, predicate) {
  6758. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6759. var el = array_1[_i];
  6760. if (predicate(el)) {
  6761. return el;
  6762. }
  6763. }
  6764. return null;
  6765. };
  6766. /**
  6767. * This method will return the name of the full name of the class, including its owning module (if any).
  6768. * 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).
  6769. * @param object the object to get the class name from
  6770. * @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.
  6771. */
  6772. Tools.getFullClassName = function (object, isType) {
  6773. if (isType === void 0) { isType = false; }
  6774. var className = null;
  6775. var moduleName = null;
  6776. if (!isType && object.getClassName) {
  6777. className = object.getClassName();
  6778. }
  6779. else {
  6780. if (object instanceof Object) {
  6781. var classObj = isType ? object : Object.getPrototypeOf(object);
  6782. className = classObj.constructor["__bjsclassName__"];
  6783. moduleName = classObj.constructor["__bjsmoduleName__"];
  6784. }
  6785. if (!className) {
  6786. className = typeof object;
  6787. }
  6788. }
  6789. if (!className) {
  6790. return null;
  6791. }
  6792. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6793. };
  6794. /**
  6795. * 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.
  6796. * @param array
  6797. */
  6798. Tools.arrayOrStringFeeder = function (array) {
  6799. return function (index) {
  6800. if (index >= array.length) {
  6801. return null;
  6802. }
  6803. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6804. if (val && val.getHashCode) {
  6805. val = val.getHashCode();
  6806. }
  6807. if (typeof val === "string") {
  6808. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6809. }
  6810. return val;
  6811. };
  6812. };
  6813. /**
  6814. * Compute the hashCode of a stream of number
  6815. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6816. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6817. * @return the hash code computed
  6818. */
  6819. Tools.hashCodeFromStream = function (feeder) {
  6820. // Based from here: http://stackoverflow.com/a/7616484/802124
  6821. var hash = 0;
  6822. var index = 0;
  6823. var chr = feeder(index++);
  6824. while (chr != null) {
  6825. hash = ((hash << 5) - hash) + chr;
  6826. hash |= 0; // Convert to 32bit integer
  6827. chr = feeder(index++);
  6828. }
  6829. return hash;
  6830. };
  6831. Tools.BaseUrl = "";
  6832. Tools.CorsBehavior = "anonymous";
  6833. Tools.UseFallbackTexture = true;
  6834. /**
  6835. * Use this object to register external classes like custom textures or material
  6836. * to allow the laoders to instantiate them
  6837. */
  6838. Tools.RegisteredExternalClasses = {};
  6839. // Used in case of a texture loading problem
  6840. 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";
  6841. Tools.PreprocessUrl = function (url) {
  6842. return url;
  6843. };
  6844. // Logs
  6845. Tools._NoneLogLevel = 0;
  6846. Tools._MessageLogLevel = 1;
  6847. Tools._WarningLogLevel = 2;
  6848. Tools._ErrorLogLevel = 4;
  6849. Tools._LogCache = "";
  6850. Tools.errorsCount = 0;
  6851. Tools.Log = Tools._LogEnabled;
  6852. Tools.Warn = Tools._WarnEnabled;
  6853. Tools.Error = Tools._ErrorEnabled;
  6854. // Performances
  6855. Tools._PerformanceNoneLogLevel = 0;
  6856. Tools._PerformanceUserMarkLogLevel = 1;
  6857. Tools._PerformanceConsoleLogLevel = 2;
  6858. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6859. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6860. return Tools;
  6861. }());
  6862. BABYLON.Tools = Tools;
  6863. /**
  6864. * This class is used to track a performance counter which is number based.
  6865. * The user has access to many properties which give statistics of different nature
  6866. *
  6867. * The implementer can track two kinds of Performance Counter: time and count
  6868. * 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.
  6869. * 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.
  6870. */
  6871. var PerfCounter = /** @class */ (function () {
  6872. function PerfCounter() {
  6873. this._startMonitoringTime = 0;
  6874. this._min = 0;
  6875. this._max = 0;
  6876. this._average = 0;
  6877. this._lastSecAverage = 0;
  6878. this._current = 0;
  6879. this._totalValueCount = 0;
  6880. this._totalAccumulated = 0;
  6881. this._lastSecAccumulated = 0;
  6882. this._lastSecTime = 0;
  6883. this._lastSecValueCount = 0;
  6884. }
  6885. Object.defineProperty(PerfCounter.prototype, "min", {
  6886. /**
  6887. * Returns the smallest value ever
  6888. */
  6889. get: function () {
  6890. return this._min;
  6891. },
  6892. enumerable: true,
  6893. configurable: true
  6894. });
  6895. Object.defineProperty(PerfCounter.prototype, "max", {
  6896. /**
  6897. * Returns the biggest value ever
  6898. */
  6899. get: function () {
  6900. return this._max;
  6901. },
  6902. enumerable: true,
  6903. configurable: true
  6904. });
  6905. Object.defineProperty(PerfCounter.prototype, "average", {
  6906. /**
  6907. * Returns the average value since the performance counter is running
  6908. */
  6909. get: function () {
  6910. return this._average;
  6911. },
  6912. enumerable: true,
  6913. configurable: true
  6914. });
  6915. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6916. /**
  6917. * Returns the average value of the last second the counter was monitored
  6918. */
  6919. get: function () {
  6920. return this._lastSecAverage;
  6921. },
  6922. enumerable: true,
  6923. configurable: true
  6924. });
  6925. Object.defineProperty(PerfCounter.prototype, "current", {
  6926. /**
  6927. * Returns the current value
  6928. */
  6929. get: function () {
  6930. return this._current;
  6931. },
  6932. enumerable: true,
  6933. configurable: true
  6934. });
  6935. Object.defineProperty(PerfCounter.prototype, "total", {
  6936. get: function () {
  6937. return this._totalAccumulated;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. /**
  6943. * Call this method to start monitoring a new frame.
  6944. * 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.
  6945. */
  6946. PerfCounter.prototype.fetchNewFrame = function () {
  6947. this._totalValueCount++;
  6948. this._current = 0;
  6949. this._lastSecValueCount++;
  6950. };
  6951. /**
  6952. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6953. * @param newCount the count value to add to the monitored count
  6954. * @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.
  6955. */
  6956. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6957. if (!PerfCounter.Enabled) {
  6958. return;
  6959. }
  6960. this._current += newCount;
  6961. if (fetchResult) {
  6962. this._fetchResult();
  6963. }
  6964. };
  6965. /**
  6966. * Start monitoring this performance counter
  6967. */
  6968. PerfCounter.prototype.beginMonitoring = function () {
  6969. if (!PerfCounter.Enabled) {
  6970. return;
  6971. }
  6972. this._startMonitoringTime = Tools.Now;
  6973. };
  6974. /**
  6975. * Compute the time lapsed since the previous beginMonitoring() call.
  6976. * @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
  6977. */
  6978. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6979. if (newFrame === void 0) { newFrame = true; }
  6980. if (!PerfCounter.Enabled) {
  6981. return;
  6982. }
  6983. if (newFrame) {
  6984. this.fetchNewFrame();
  6985. }
  6986. var currentTime = Tools.Now;
  6987. this._current = currentTime - this._startMonitoringTime;
  6988. if (newFrame) {
  6989. this._fetchResult();
  6990. }
  6991. };
  6992. PerfCounter.prototype._fetchResult = function () {
  6993. this._totalAccumulated += this._current;
  6994. this._lastSecAccumulated += this._current;
  6995. // Min/Max update
  6996. this._min = Math.min(this._min, this._current);
  6997. this._max = Math.max(this._max, this._current);
  6998. this._average = this._totalAccumulated / this._totalValueCount;
  6999. // Reset last sec?
  7000. var now = Tools.Now;
  7001. if ((now - this._lastSecTime) > 1000) {
  7002. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7003. this._lastSecTime = now;
  7004. this._lastSecAccumulated = 0;
  7005. this._lastSecValueCount = 0;
  7006. }
  7007. };
  7008. PerfCounter.Enabled = true;
  7009. return PerfCounter;
  7010. }());
  7011. BABYLON.PerfCounter = PerfCounter;
  7012. /**
  7013. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7014. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7015. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7016. * @param name The name of the class, case should be preserved
  7017. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7018. */
  7019. function className(name, module) {
  7020. return function (target) {
  7021. target["__bjsclassName__"] = name;
  7022. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7023. };
  7024. }
  7025. BABYLON.className = className;
  7026. /**
  7027. * An implementation of a loop for asynchronous functions.
  7028. */
  7029. var AsyncLoop = /** @class */ (function () {
  7030. /**
  7031. * Constroctor.
  7032. * @param iterations the number of iterations.
  7033. * @param _fn the function to run each iteration
  7034. * @param _successCallback the callback that will be called upon succesful execution
  7035. * @param offset starting offset.
  7036. */
  7037. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7038. if (offset === void 0) { offset = 0; }
  7039. this.iterations = iterations;
  7040. this._fn = _fn;
  7041. this._successCallback = _successCallback;
  7042. this.index = offset - 1;
  7043. this._done = false;
  7044. }
  7045. /**
  7046. * Execute the next iteration. Must be called after the last iteration was finished.
  7047. */
  7048. AsyncLoop.prototype.executeNext = function () {
  7049. if (!this._done) {
  7050. if (this.index + 1 < this.iterations) {
  7051. ++this.index;
  7052. this._fn(this);
  7053. }
  7054. else {
  7055. this.breakLoop();
  7056. }
  7057. }
  7058. };
  7059. /**
  7060. * Break the loop and run the success callback.
  7061. */
  7062. AsyncLoop.prototype.breakLoop = function () {
  7063. this._done = true;
  7064. this._successCallback();
  7065. };
  7066. /**
  7067. * Helper function
  7068. */
  7069. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7070. if (offset === void 0) { offset = 0; }
  7071. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7072. loop.executeNext();
  7073. return loop;
  7074. };
  7075. /**
  7076. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7077. * @param iterations total number of iterations
  7078. * @param syncedIterations number of synchronous iterations in each async iteration.
  7079. * @param fn the function to call each iteration.
  7080. * @param callback a success call back that will be called when iterating stops.
  7081. * @param breakFunction a break condition (optional)
  7082. * @param timeout timeout settings for the setTimeout function. default - 0.
  7083. * @constructor
  7084. */
  7085. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7086. if (timeout === void 0) { timeout = 0; }
  7087. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7088. if (breakFunction && breakFunction())
  7089. loop.breakLoop();
  7090. else {
  7091. setTimeout(function () {
  7092. for (var i = 0; i < syncedIterations; ++i) {
  7093. var iteration = (loop.index * syncedIterations) + i;
  7094. if (iteration >= iterations)
  7095. break;
  7096. fn(iteration);
  7097. if (breakFunction && breakFunction()) {
  7098. loop.breakLoop();
  7099. break;
  7100. }
  7101. }
  7102. loop.executeNext();
  7103. }, timeout);
  7104. }
  7105. }, callback);
  7106. };
  7107. return AsyncLoop;
  7108. }());
  7109. BABYLON.AsyncLoop = AsyncLoop;
  7110. })(BABYLON || (BABYLON = {}));
  7111. //# sourceMappingURL=babylon.tools.js.map
  7112. var BABYLON;
  7113. (function (BABYLON) {
  7114. var Internals;
  7115. (function (Internals) {
  7116. var _AlphaState = /** @class */ (function () {
  7117. /**
  7118. * Initializes the state.
  7119. */
  7120. function _AlphaState() {
  7121. this._isAlphaBlendDirty = false;
  7122. this._isBlendFunctionParametersDirty = false;
  7123. this._isBlendEquationParametersDirty = false;
  7124. this._isBlendConstantsDirty = false;
  7125. this._alphaBlend = false;
  7126. this._blendFunctionParameters = new Array(4);
  7127. this._blendEquationParameters = new Array(2);
  7128. this._blendConstants = new Array(4);
  7129. this.reset();
  7130. }
  7131. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7132. get: function () {
  7133. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7134. },
  7135. enumerable: true,
  7136. configurable: true
  7137. });
  7138. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7139. get: function () {
  7140. return this._alphaBlend;
  7141. },
  7142. set: function (value) {
  7143. if (this._alphaBlend === value) {
  7144. return;
  7145. }
  7146. this._alphaBlend = value;
  7147. this._isAlphaBlendDirty = true;
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7153. if (this._blendConstants[0] === r &&
  7154. this._blendConstants[1] === g &&
  7155. this._blendConstants[2] === b &&
  7156. this._blendConstants[3] === a) {
  7157. return;
  7158. }
  7159. this._blendConstants[0] = r;
  7160. this._blendConstants[1] = g;
  7161. this._blendConstants[2] = b;
  7162. this._blendConstants[3] = a;
  7163. this._isBlendConstantsDirty = true;
  7164. };
  7165. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7166. if (this._blendFunctionParameters[0] === value0 &&
  7167. this._blendFunctionParameters[1] === value1 &&
  7168. this._blendFunctionParameters[2] === value2 &&
  7169. this._blendFunctionParameters[3] === value3) {
  7170. return;
  7171. }
  7172. this._blendFunctionParameters[0] = value0;
  7173. this._blendFunctionParameters[1] = value1;
  7174. this._blendFunctionParameters[2] = value2;
  7175. this._blendFunctionParameters[3] = value3;
  7176. this._isBlendFunctionParametersDirty = true;
  7177. };
  7178. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7179. if (this._blendEquationParameters[0] === rgb &&
  7180. this._blendEquationParameters[1] === alpha) {
  7181. return;
  7182. }
  7183. this._blendEquationParameters[0] = rgb;
  7184. this._blendEquationParameters[1] = alpha;
  7185. this._isBlendEquationParametersDirty = true;
  7186. };
  7187. _AlphaState.prototype.reset = function () {
  7188. this._alphaBlend = false;
  7189. this._blendFunctionParameters[0] = null;
  7190. this._blendFunctionParameters[1] = null;
  7191. this._blendFunctionParameters[2] = null;
  7192. this._blendFunctionParameters[3] = null;
  7193. this._blendEquationParameters[0] = null;
  7194. this._blendEquationParameters[1] = null;
  7195. this._blendConstants[0] = null;
  7196. this._blendConstants[1] = null;
  7197. this._blendConstants[2] = null;
  7198. this._blendConstants[3] = null;
  7199. this._isAlphaBlendDirty = true;
  7200. this._isBlendFunctionParametersDirty = false;
  7201. this._isBlendEquationParametersDirty = false;
  7202. this._isBlendConstantsDirty = false;
  7203. };
  7204. _AlphaState.prototype.apply = function (gl) {
  7205. if (!this.isDirty) {
  7206. return;
  7207. }
  7208. // Alpha blend
  7209. if (this._isAlphaBlendDirty) {
  7210. if (this._alphaBlend) {
  7211. gl.enable(gl.BLEND);
  7212. }
  7213. else {
  7214. gl.disable(gl.BLEND);
  7215. }
  7216. this._isAlphaBlendDirty = false;
  7217. }
  7218. // Alpha function
  7219. if (this._isBlendFunctionParametersDirty) {
  7220. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7221. this._isBlendFunctionParametersDirty = false;
  7222. }
  7223. // Alpha equation
  7224. if (this._isBlendEquationParametersDirty) {
  7225. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7226. this._isBlendEquationParametersDirty = false;
  7227. }
  7228. // Constants
  7229. if (this._isBlendConstantsDirty) {
  7230. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7231. this._isBlendConstantsDirty = false;
  7232. }
  7233. };
  7234. return _AlphaState;
  7235. }());
  7236. Internals._AlphaState = _AlphaState;
  7237. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7238. })(BABYLON || (BABYLON = {}));
  7239. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7240. var BABYLON;
  7241. (function (BABYLON) {
  7242. var Internals;
  7243. (function (Internals) {
  7244. var _DepthCullingState = /** @class */ (function () {
  7245. /**
  7246. * Initializes the state.
  7247. */
  7248. function _DepthCullingState() {
  7249. this._isDepthTestDirty = false;
  7250. this._isDepthMaskDirty = false;
  7251. this._isDepthFuncDirty = false;
  7252. this._isCullFaceDirty = false;
  7253. this._isCullDirty = false;
  7254. this._isZOffsetDirty = false;
  7255. this.reset();
  7256. }
  7257. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7258. get: function () {
  7259. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7260. },
  7261. enumerable: true,
  7262. configurable: true
  7263. });
  7264. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7265. get: function () {
  7266. return this._zOffset;
  7267. },
  7268. set: function (value) {
  7269. if (this._zOffset === value) {
  7270. return;
  7271. }
  7272. this._zOffset = value;
  7273. this._isZOffsetDirty = true;
  7274. },
  7275. enumerable: true,
  7276. configurable: true
  7277. });
  7278. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7279. get: function () {
  7280. return this._cullFace;
  7281. },
  7282. set: function (value) {
  7283. if (this._cullFace === value) {
  7284. return;
  7285. }
  7286. this._cullFace = value;
  7287. this._isCullFaceDirty = true;
  7288. },
  7289. enumerable: true,
  7290. configurable: true
  7291. });
  7292. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7293. get: function () {
  7294. return this._cull;
  7295. },
  7296. set: function (value) {
  7297. if (this._cull === value) {
  7298. return;
  7299. }
  7300. this._cull = value;
  7301. this._isCullDirty = true;
  7302. },
  7303. enumerable: true,
  7304. configurable: true
  7305. });
  7306. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7307. get: function () {
  7308. return this._depthFunc;
  7309. },
  7310. set: function (value) {
  7311. if (this._depthFunc === value) {
  7312. return;
  7313. }
  7314. this._depthFunc = value;
  7315. this._isDepthFuncDirty = true;
  7316. },
  7317. enumerable: true,
  7318. configurable: true
  7319. });
  7320. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7321. get: function () {
  7322. return this._depthMask;
  7323. },
  7324. set: function (value) {
  7325. if (this._depthMask === value) {
  7326. return;
  7327. }
  7328. this._depthMask = value;
  7329. this._isDepthMaskDirty = true;
  7330. },
  7331. enumerable: true,
  7332. configurable: true
  7333. });
  7334. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7335. get: function () {
  7336. return this._depthTest;
  7337. },
  7338. set: function (value) {
  7339. if (this._depthTest === value) {
  7340. return;
  7341. }
  7342. this._depthTest = value;
  7343. this._isDepthTestDirty = true;
  7344. },
  7345. enumerable: true,
  7346. configurable: true
  7347. });
  7348. _DepthCullingState.prototype.reset = function () {
  7349. this._depthMask = true;
  7350. this._depthTest = true;
  7351. this._depthFunc = null;
  7352. this._cullFace = null;
  7353. this._cull = null;
  7354. this._zOffset = 0;
  7355. this._isDepthTestDirty = true;
  7356. this._isDepthMaskDirty = true;
  7357. this._isDepthFuncDirty = false;
  7358. this._isCullFaceDirty = false;
  7359. this._isCullDirty = false;
  7360. this._isZOffsetDirty = false;
  7361. };
  7362. _DepthCullingState.prototype.apply = function (gl) {
  7363. if (!this.isDirty) {
  7364. return;
  7365. }
  7366. // Cull
  7367. if (this._isCullDirty) {
  7368. if (this.cull) {
  7369. gl.enable(gl.CULL_FACE);
  7370. }
  7371. else {
  7372. gl.disable(gl.CULL_FACE);
  7373. }
  7374. this._isCullDirty = false;
  7375. }
  7376. // Cull face
  7377. if (this._isCullFaceDirty) {
  7378. gl.cullFace(this.cullFace);
  7379. this._isCullFaceDirty = false;
  7380. }
  7381. // Depth mask
  7382. if (this._isDepthMaskDirty) {
  7383. gl.depthMask(this.depthMask);
  7384. this._isDepthMaskDirty = false;
  7385. }
  7386. // Depth test
  7387. if (this._isDepthTestDirty) {
  7388. if (this.depthTest) {
  7389. gl.enable(gl.DEPTH_TEST);
  7390. }
  7391. else {
  7392. gl.disable(gl.DEPTH_TEST);
  7393. }
  7394. this._isDepthTestDirty = false;
  7395. }
  7396. // Depth func
  7397. if (this._isDepthFuncDirty) {
  7398. gl.depthFunc(this.depthFunc);
  7399. this._isDepthFuncDirty = false;
  7400. }
  7401. // zOffset
  7402. if (this._isZOffsetDirty) {
  7403. if (this.zOffset) {
  7404. gl.enable(gl.POLYGON_OFFSET_FILL);
  7405. gl.polygonOffset(this.zOffset, 0);
  7406. }
  7407. else {
  7408. gl.disable(gl.POLYGON_OFFSET_FILL);
  7409. }
  7410. this._isZOffsetDirty = false;
  7411. }
  7412. };
  7413. return _DepthCullingState;
  7414. }());
  7415. Internals._DepthCullingState = _DepthCullingState;
  7416. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7417. })(BABYLON || (BABYLON = {}));
  7418. //# sourceMappingURL=babylon.depthCullingState.js.map
  7419. var BABYLON;
  7420. (function (BABYLON) {
  7421. var Internals;
  7422. (function (Internals) {
  7423. var _StencilState = /** @class */ (function () {
  7424. function _StencilState() {
  7425. this._isStencilTestDirty = false;
  7426. this._isStencilMaskDirty = false;
  7427. this._isStencilFuncDirty = false;
  7428. this._isStencilOpDirty = false;
  7429. this.reset();
  7430. }
  7431. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7432. get: function () {
  7433. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7434. },
  7435. enumerable: true,
  7436. configurable: true
  7437. });
  7438. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7439. get: function () {
  7440. return this._stencilFunc;
  7441. },
  7442. set: function (value) {
  7443. if (this._stencilFunc === value) {
  7444. return;
  7445. }
  7446. this._stencilFunc = value;
  7447. this._isStencilFuncDirty = true;
  7448. },
  7449. enumerable: true,
  7450. configurable: true
  7451. });
  7452. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7453. get: function () {
  7454. return this._stencilFuncRef;
  7455. },
  7456. set: function (value) {
  7457. if (this._stencilFuncRef === value) {
  7458. return;
  7459. }
  7460. this._stencilFuncRef = value;
  7461. this._isStencilFuncDirty = true;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7467. get: function () {
  7468. return this._stencilFuncMask;
  7469. },
  7470. set: function (value) {
  7471. if (this._stencilFuncMask === value) {
  7472. return;
  7473. }
  7474. this._stencilFuncMask = value;
  7475. this._isStencilFuncDirty = true;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7481. get: function () {
  7482. return this._stencilOpStencilFail;
  7483. },
  7484. set: function (value) {
  7485. if (this._stencilOpStencilFail === value) {
  7486. return;
  7487. }
  7488. this._stencilOpStencilFail = value;
  7489. this._isStencilOpDirty = true;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7495. get: function () {
  7496. return this._stencilOpDepthFail;
  7497. },
  7498. set: function (value) {
  7499. if (this._stencilOpDepthFail === value) {
  7500. return;
  7501. }
  7502. this._stencilOpDepthFail = value;
  7503. this._isStencilOpDirty = true;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7509. get: function () {
  7510. return this._stencilOpStencilDepthPass;
  7511. },
  7512. set: function (value) {
  7513. if (this._stencilOpStencilDepthPass === value) {
  7514. return;
  7515. }
  7516. this._stencilOpStencilDepthPass = value;
  7517. this._isStencilOpDirty = true;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7523. get: function () {
  7524. return this._stencilMask;
  7525. },
  7526. set: function (value) {
  7527. if (this._stencilMask === value) {
  7528. return;
  7529. }
  7530. this._stencilMask = value;
  7531. this._isStencilMaskDirty = true;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7537. get: function () {
  7538. return this._stencilTest;
  7539. },
  7540. set: function (value) {
  7541. if (this._stencilTest === value) {
  7542. return;
  7543. }
  7544. this._stencilTest = value;
  7545. this._isStencilTestDirty = true;
  7546. },
  7547. enumerable: true,
  7548. configurable: true
  7549. });
  7550. _StencilState.prototype.reset = function () {
  7551. this._stencilTest = false;
  7552. this._stencilMask = 0xFF;
  7553. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7554. this._stencilFuncRef = 1;
  7555. this._stencilFuncMask = 0xFF;
  7556. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7557. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7558. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7559. this._isStencilTestDirty = true;
  7560. this._isStencilMaskDirty = true;
  7561. this._isStencilFuncDirty = true;
  7562. this._isStencilOpDirty = true;
  7563. };
  7564. _StencilState.prototype.apply = function (gl) {
  7565. if (!this.isDirty) {
  7566. return;
  7567. }
  7568. // Stencil test
  7569. if (this._isStencilTestDirty) {
  7570. if (this.stencilTest) {
  7571. gl.enable(gl.STENCIL_TEST);
  7572. }
  7573. else {
  7574. gl.disable(gl.STENCIL_TEST);
  7575. }
  7576. this._isStencilTestDirty = false;
  7577. }
  7578. // Stencil mask
  7579. if (this._isStencilMaskDirty) {
  7580. gl.stencilMask(this.stencilMask);
  7581. this._isStencilMaskDirty = false;
  7582. }
  7583. // Stencil func
  7584. if (this._isStencilFuncDirty) {
  7585. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7586. this._isStencilFuncDirty = false;
  7587. }
  7588. // Stencil op
  7589. if (this._isStencilOpDirty) {
  7590. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7591. this._isStencilOpDirty = false;
  7592. }
  7593. };
  7594. return _StencilState;
  7595. }());
  7596. Internals._StencilState = _StencilState;
  7597. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7598. })(BABYLON || (BABYLON = {}));
  7599. //# sourceMappingURL=babylon.stencilState.js.map
  7600. var BABYLON;
  7601. (function (BABYLON) {
  7602. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7603. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7604. };
  7605. var compileRawShader = function (gl, source, type) {
  7606. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7607. gl.shaderSource(shader, source);
  7608. gl.compileShader(shader);
  7609. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7610. var log = gl.getShaderInfoLog(shader);
  7611. if (log) {
  7612. throw new Error(log);
  7613. }
  7614. }
  7615. if (!shader) {
  7616. throw new Error("Something went wrong while compile the shader.");
  7617. }
  7618. return shader;
  7619. };
  7620. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7621. var magFilter = gl.NEAREST;
  7622. var minFilter = gl.NEAREST;
  7623. switch (samplingMode) {
  7624. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7625. magFilter = gl.LINEAR;
  7626. if (generateMipMaps) {
  7627. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7628. }
  7629. else {
  7630. minFilter = gl.LINEAR;
  7631. }
  7632. break;
  7633. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7634. magFilter = gl.LINEAR;
  7635. if (generateMipMaps) {
  7636. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7637. }
  7638. else {
  7639. minFilter = gl.LINEAR;
  7640. }
  7641. break;
  7642. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7643. magFilter = gl.NEAREST;
  7644. if (generateMipMaps) {
  7645. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7646. }
  7647. else {
  7648. minFilter = gl.NEAREST;
  7649. }
  7650. break;
  7651. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7652. magFilter = gl.NEAREST;
  7653. if (generateMipMaps) {
  7654. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7655. }
  7656. else {
  7657. minFilter = gl.NEAREST;
  7658. }
  7659. break;
  7660. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7661. magFilter = gl.NEAREST;
  7662. if (generateMipMaps) {
  7663. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7664. }
  7665. else {
  7666. minFilter = gl.LINEAR;
  7667. }
  7668. break;
  7669. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7670. magFilter = gl.NEAREST;
  7671. if (generateMipMaps) {
  7672. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7673. }
  7674. else {
  7675. minFilter = gl.LINEAR;
  7676. }
  7677. break;
  7678. case BABYLON.Texture.NEAREST_LINEAR:
  7679. magFilter = gl.NEAREST;
  7680. minFilter = gl.LINEAR;
  7681. break;
  7682. case BABYLON.Texture.NEAREST_NEAREST:
  7683. magFilter = gl.NEAREST;
  7684. minFilter = gl.NEAREST;
  7685. break;
  7686. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7687. magFilter = gl.LINEAR;
  7688. if (generateMipMaps) {
  7689. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7690. }
  7691. else {
  7692. minFilter = gl.NEAREST;
  7693. }
  7694. break;
  7695. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7696. magFilter = gl.LINEAR;
  7697. if (generateMipMaps) {
  7698. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7699. }
  7700. else {
  7701. minFilter = gl.NEAREST;
  7702. }
  7703. break;
  7704. case BABYLON.Texture.LINEAR_LINEAR:
  7705. magFilter = gl.LINEAR;
  7706. minFilter = gl.LINEAR;
  7707. break;
  7708. case BABYLON.Texture.LINEAR_NEAREST:
  7709. magFilter = gl.LINEAR;
  7710. minFilter = gl.NEAREST;
  7711. break;
  7712. }
  7713. return {
  7714. min: minFilter,
  7715. mag: magFilter
  7716. };
  7717. };
  7718. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7719. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7720. var img;
  7721. var onload = function () {
  7722. loadedImages[index] = img;
  7723. loadedImages._internalCount++;
  7724. if (scene) {
  7725. scene._removePendingData(img);
  7726. }
  7727. if (loadedImages._internalCount === 6) {
  7728. onfinish(loadedImages);
  7729. }
  7730. };
  7731. var onerror = function (message, exception) {
  7732. if (scene) {
  7733. scene._removePendingData(img);
  7734. }
  7735. if (onErrorCallBack) {
  7736. onErrorCallBack(message, exception);
  7737. }
  7738. };
  7739. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7740. if (scene) {
  7741. scene._addPendingData(img);
  7742. }
  7743. };
  7744. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7745. if (onError === void 0) { onError = null; }
  7746. var loadedImages = [];
  7747. loadedImages._internalCount = 0;
  7748. for (var index = 0; index < 6; index++) {
  7749. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7750. }
  7751. };
  7752. var BufferPointer = /** @class */ (function () {
  7753. function BufferPointer() {
  7754. }
  7755. return BufferPointer;
  7756. }());
  7757. var InstancingAttributeInfo = /** @class */ (function () {
  7758. function InstancingAttributeInfo() {
  7759. }
  7760. return InstancingAttributeInfo;
  7761. }());
  7762. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7763. /**
  7764. * Define options used to create a render target texture
  7765. */
  7766. var RenderTargetCreationOptions = /** @class */ (function () {
  7767. function RenderTargetCreationOptions() {
  7768. }
  7769. return RenderTargetCreationOptions;
  7770. }());
  7771. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7772. /**
  7773. * Regroup several parameters relative to the browser in use
  7774. */
  7775. var EngineCapabilities = /** @class */ (function () {
  7776. function EngineCapabilities() {
  7777. }
  7778. return EngineCapabilities;
  7779. }());
  7780. BABYLON.EngineCapabilities = EngineCapabilities;
  7781. /**
  7782. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7783. */
  7784. var Engine = /** @class */ (function () {
  7785. /**
  7786. * @constructor
  7787. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7788. * @param {boolean} [antialias] - enable antialias
  7789. * @param options - further options to be sent to the getContext function
  7790. */
  7791. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7792. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7793. var _this = this;
  7794. // Public members
  7795. this.forcePOTTextures = false;
  7796. this.isFullscreen = false;
  7797. this.isPointerLock = false;
  7798. this.cullBackFaces = true;
  7799. this.renderEvenInBackground = true;
  7800. this.preventCacheWipeBetweenFrames = false;
  7801. // To enable/disable IDB support and avoid XHR on .manifest
  7802. this.enableOfflineSupport = false;
  7803. this.scenes = new Array();
  7804. this.postProcesses = new Array();
  7805. // Observables
  7806. /**
  7807. * Observable event triggered each time the rendering canvas is resized
  7808. */
  7809. this.onResizeObservable = new BABYLON.Observable();
  7810. /**
  7811. * Observable event triggered each time the canvas loses focus
  7812. */
  7813. this.onCanvasBlurObservable = new BABYLON.Observable();
  7814. /**
  7815. * Observable event triggered each time the canvas gains focus
  7816. */
  7817. this.onCanvasFocusObservable = new BABYLON.Observable();
  7818. /**
  7819. * Observable event triggered each time the canvas receives pointerout event
  7820. */
  7821. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7822. /**
  7823. * Observable event triggered before each texture is initialized
  7824. */
  7825. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7826. //WebVR
  7827. this._vrDisplay = undefined;
  7828. this._vrSupported = false;
  7829. this._vrExclusivePointerMode = false;
  7830. // Uniform buffers list
  7831. this.disableUniformBuffers = false;
  7832. this._uniformBuffers = new Array();
  7833. this._windowIsBackground = false;
  7834. this._webGLVersion = 1.0;
  7835. this._badOS = false;
  7836. this._badDesktopOS = false;
  7837. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7838. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7839. this.onVRRequestPresentStart = new BABYLON.Observable();
  7840. this._colorWrite = true;
  7841. this._drawCalls = new BABYLON.PerfCounter();
  7842. this._renderingQueueLaunched = false;
  7843. this._activeRenderLoops = new Array();
  7844. // Deterministic lockstepMaxSteps
  7845. this._deterministicLockstep = false;
  7846. this._lockstepMaxSteps = 4;
  7847. // Lost context
  7848. this.onContextLostObservable = new BABYLON.Observable();
  7849. this.onContextRestoredObservable = new BABYLON.Observable();
  7850. this._contextWasLost = false;
  7851. this._doNotHandleContextLost = false;
  7852. // FPS
  7853. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7854. this._fps = 60;
  7855. this._deltaTime = 0;
  7856. /**
  7857. * Turn this value on if you want to pause FPS computation when in background
  7858. */
  7859. this.disablePerformanceMonitorInBackground = false;
  7860. // States
  7861. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7862. this._stencilState = new BABYLON.Internals._StencilState();
  7863. this._alphaState = new BABYLON.Internals._AlphaState();
  7864. this._alphaMode = Engine.ALPHA_DISABLE;
  7865. // Cache
  7866. this._internalTexturesCache = new Array();
  7867. this._activeTexturesCache = {};
  7868. this._compiledEffects = {};
  7869. this._vertexAttribArraysEnabled = [];
  7870. this._uintIndicesCurrentlySet = false;
  7871. this._currentBoundBuffer = new Array();
  7872. this._currentBufferPointers = new Array();
  7873. this._currentInstanceLocations = new Array();
  7874. this._currentInstanceBuffers = new Array();
  7875. this._vaoRecordInProgress = false;
  7876. this._mustWipeVertexAttributes = false;
  7877. // Hardware supported Compressed Textures
  7878. this._texturesSupported = new Array();
  7879. this._onVRFullScreenTriggered = function () {
  7880. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7881. //get the old size before we change
  7882. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7883. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7884. //get the width and height, change the render size
  7885. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7886. _this.setHardwareScalingLevel(1);
  7887. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7888. }
  7889. else {
  7890. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7891. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7892. }
  7893. };
  7894. var canvas = null;
  7895. Engine.Instances.push(this);
  7896. if (!canvasOrContext) {
  7897. return;
  7898. }
  7899. options = options || {};
  7900. if (canvasOrContext.getContext) {
  7901. canvas = canvasOrContext;
  7902. this._renderingCanvas = canvas;
  7903. if (antialias != null) {
  7904. options.antialias = antialias;
  7905. }
  7906. if (options.deterministicLockstep === undefined) {
  7907. options.deterministicLockstep = false;
  7908. }
  7909. if (options.lockstepMaxSteps === undefined) {
  7910. options.lockstepMaxSteps = 4;
  7911. }
  7912. if (options.preserveDrawingBuffer === undefined) {
  7913. options.preserveDrawingBuffer = false;
  7914. }
  7915. if (options.audioEngine === undefined) {
  7916. options.audioEngine = true;
  7917. }
  7918. if (options.stencil === undefined) {
  7919. options.stencil = true;
  7920. }
  7921. this._deterministicLockstep = options.deterministicLockstep;
  7922. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7923. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7924. // GL
  7925. if (!options.disableWebGL2Support) {
  7926. try {
  7927. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7928. if (this._gl) {
  7929. this._webGLVersion = 2.0;
  7930. }
  7931. }
  7932. catch (e) {
  7933. // Do nothing
  7934. }
  7935. }
  7936. if (!this._gl) {
  7937. if (!canvas) {
  7938. throw new Error("The provided canvas is null or undefined.");
  7939. }
  7940. try {
  7941. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7942. }
  7943. catch (e) {
  7944. throw new Error("WebGL not supported");
  7945. }
  7946. }
  7947. if (!this._gl) {
  7948. throw new Error("WebGL not supported");
  7949. }
  7950. this._onCanvasFocus = function () {
  7951. _this.onCanvasFocusObservable.notifyObservers(_this);
  7952. };
  7953. this._onCanvasBlur = function () {
  7954. _this.onCanvasBlurObservable.notifyObservers(_this);
  7955. };
  7956. canvas.addEventListener("focus", this._onCanvasFocus);
  7957. canvas.addEventListener("blur", this._onCanvasBlur);
  7958. this._onBlur = function () {
  7959. if (_this.disablePerformanceMonitorInBackground) {
  7960. _this._performanceMonitor.disable();
  7961. }
  7962. _this._windowIsBackground = true;
  7963. };
  7964. this._onFocus = function () {
  7965. if (_this.disablePerformanceMonitorInBackground) {
  7966. _this._performanceMonitor.enable();
  7967. }
  7968. _this._windowIsBackground = false;
  7969. };
  7970. this._onCanvasPointerOut = function () {
  7971. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7972. };
  7973. window.addEventListener("blur", this._onBlur);
  7974. window.addEventListener("focus", this._onFocus);
  7975. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7976. // Context lost
  7977. if (!this._doNotHandleContextLost) {
  7978. this._onContextLost = function (evt) {
  7979. evt.preventDefault();
  7980. _this._contextWasLost = true;
  7981. BABYLON.Tools.Warn("WebGL context lost.");
  7982. _this.onContextLostObservable.notifyObservers(_this);
  7983. };
  7984. this._onContextRestored = function (evt) {
  7985. // Adding a timeout to avoid race condition at browser level
  7986. setTimeout(function () {
  7987. // Rebuild gl context
  7988. _this._initGLContext();
  7989. // Rebuild effects
  7990. _this._rebuildEffects();
  7991. // Rebuild textures
  7992. _this._rebuildInternalTextures();
  7993. // Rebuild buffers
  7994. _this._rebuildBuffers();
  7995. // Cache
  7996. _this.wipeCaches(true);
  7997. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7998. _this.onContextRestoredObservable.notifyObservers(_this);
  7999. _this._contextWasLost = false;
  8000. }, 0);
  8001. };
  8002. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8003. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8004. }
  8005. }
  8006. else {
  8007. this._gl = canvasOrContext;
  8008. this._renderingCanvas = this._gl.canvas;
  8009. if (this._gl.renderbufferStorageMultisample) {
  8010. this._webGLVersion = 2.0;
  8011. }
  8012. options.stencil = this._gl.getContextAttributes().stencil;
  8013. }
  8014. // Viewport
  8015. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8016. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8017. this.resize();
  8018. this._isStencilEnable = options.stencil ? true : false;
  8019. this._initGLContext();
  8020. if (canvas) {
  8021. // Fullscreen
  8022. this._onFullscreenChange = function () {
  8023. if (document.fullscreen !== undefined) {
  8024. _this.isFullscreen = document.fullscreen;
  8025. }
  8026. else if (document.mozFullScreen !== undefined) {
  8027. _this.isFullscreen = document.mozFullScreen;
  8028. }
  8029. else if (document.webkitIsFullScreen !== undefined) {
  8030. _this.isFullscreen = document.webkitIsFullScreen;
  8031. }
  8032. else if (document.msIsFullScreen !== undefined) {
  8033. _this.isFullscreen = document.msIsFullScreen;
  8034. }
  8035. // Pointer lock
  8036. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8037. canvas.requestPointerLock = canvas.requestPointerLock ||
  8038. canvas.msRequestPointerLock ||
  8039. canvas.mozRequestPointerLock ||
  8040. canvas.webkitRequestPointerLock;
  8041. if (canvas.requestPointerLock) {
  8042. canvas.requestPointerLock();
  8043. }
  8044. }
  8045. };
  8046. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8047. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8048. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8049. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8050. // Pointer lock
  8051. this._onPointerLockChange = function () {
  8052. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8053. document.webkitPointerLockElement === canvas ||
  8054. document.msPointerLockElement === canvas ||
  8055. document.pointerLockElement === canvas);
  8056. };
  8057. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8058. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8059. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8060. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8061. this._onVRDisplayPointerRestricted = function () {
  8062. if (canvas) {
  8063. canvas.requestPointerLock();
  8064. }
  8065. };
  8066. this._onVRDisplayPointerUnrestricted = function () {
  8067. document.exitPointerLock();
  8068. };
  8069. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8070. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8071. }
  8072. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8073. Engine.audioEngine = new BABYLON.AudioEngine();
  8074. }
  8075. // Prepare buffer pointers
  8076. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8077. this._currentBufferPointers[i] = new BufferPointer();
  8078. }
  8079. // Load WebVR Devices
  8080. if (options.autoEnableWebVR) {
  8081. this.initWebVR();
  8082. }
  8083. // Detect if we are running on a faulty buggy OS.
  8084. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8085. // Detect if we are running on a faulty buggy desktop OS.
  8086. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8087. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8088. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8089. }
  8090. Object.defineProperty(Engine, "LastCreatedEngine", {
  8091. get: function () {
  8092. if (Engine.Instances.length === 0) {
  8093. return null;
  8094. }
  8095. return Engine.Instances[Engine.Instances.length - 1];
  8096. },
  8097. enumerable: true,
  8098. configurable: true
  8099. });
  8100. Object.defineProperty(Engine, "LastCreatedScene", {
  8101. get: function () {
  8102. var lastCreatedEngine = Engine.LastCreatedEngine;
  8103. if (!lastCreatedEngine) {
  8104. return null;
  8105. }
  8106. if (lastCreatedEngine.scenes.length === 0) {
  8107. return null;
  8108. }
  8109. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8110. },
  8111. enumerable: true,
  8112. configurable: true
  8113. });
  8114. /**
  8115. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8116. */
  8117. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8118. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8119. var engine = Engine.Instances[engineIndex];
  8120. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8121. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8122. }
  8123. }
  8124. };
  8125. Object.defineProperty(Engine, "NEVER", {
  8126. get: function () {
  8127. return Engine._NEVER;
  8128. },
  8129. enumerable: true,
  8130. configurable: true
  8131. });
  8132. Object.defineProperty(Engine, "ALWAYS", {
  8133. get: function () {
  8134. return Engine._ALWAYS;
  8135. },
  8136. enumerable: true,
  8137. configurable: true
  8138. });
  8139. Object.defineProperty(Engine, "LESS", {
  8140. get: function () {
  8141. return Engine._LESS;
  8142. },
  8143. enumerable: true,
  8144. configurable: true
  8145. });
  8146. Object.defineProperty(Engine, "EQUAL", {
  8147. get: function () {
  8148. return Engine._EQUAL;
  8149. },
  8150. enumerable: true,
  8151. configurable: true
  8152. });
  8153. Object.defineProperty(Engine, "LEQUAL", {
  8154. get: function () {
  8155. return Engine._LEQUAL;
  8156. },
  8157. enumerable: true,
  8158. configurable: true
  8159. });
  8160. Object.defineProperty(Engine, "GREATER", {
  8161. get: function () {
  8162. return Engine._GREATER;
  8163. },
  8164. enumerable: true,
  8165. configurable: true
  8166. });
  8167. Object.defineProperty(Engine, "GEQUAL", {
  8168. get: function () {
  8169. return Engine._GEQUAL;
  8170. },
  8171. enumerable: true,
  8172. configurable: true
  8173. });
  8174. Object.defineProperty(Engine, "NOTEQUAL", {
  8175. get: function () {
  8176. return Engine._NOTEQUAL;
  8177. },
  8178. enumerable: true,
  8179. configurable: true
  8180. });
  8181. Object.defineProperty(Engine, "KEEP", {
  8182. get: function () {
  8183. return Engine._KEEP;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. Object.defineProperty(Engine, "REPLACE", {
  8189. get: function () {
  8190. return Engine._REPLACE;
  8191. },
  8192. enumerable: true,
  8193. configurable: true
  8194. });
  8195. Object.defineProperty(Engine, "INCR", {
  8196. get: function () {
  8197. return Engine._INCR;
  8198. },
  8199. enumerable: true,
  8200. configurable: true
  8201. });
  8202. Object.defineProperty(Engine, "DECR", {
  8203. get: function () {
  8204. return Engine._DECR;
  8205. },
  8206. enumerable: true,
  8207. configurable: true
  8208. });
  8209. Object.defineProperty(Engine, "INVERT", {
  8210. get: function () {
  8211. return Engine._INVERT;
  8212. },
  8213. enumerable: true,
  8214. configurable: true
  8215. });
  8216. Object.defineProperty(Engine, "INCR_WRAP", {
  8217. get: function () {
  8218. return Engine._INCR_WRAP;
  8219. },
  8220. enumerable: true,
  8221. configurable: true
  8222. });
  8223. Object.defineProperty(Engine, "DECR_WRAP", {
  8224. get: function () {
  8225. return Engine._DECR_WRAP;
  8226. },
  8227. enumerable: true,
  8228. configurable: true
  8229. });
  8230. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8231. get: function () {
  8232. return Engine._ALPHA_DISABLE;
  8233. },
  8234. enumerable: true,
  8235. configurable: true
  8236. });
  8237. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8238. get: function () {
  8239. return Engine._ALPHA_ONEONE;
  8240. },
  8241. enumerable: true,
  8242. configurable: true
  8243. });
  8244. Object.defineProperty(Engine, "ALPHA_ADD", {
  8245. get: function () {
  8246. return Engine._ALPHA_ADD;
  8247. },
  8248. enumerable: true,
  8249. configurable: true
  8250. });
  8251. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8252. get: function () {
  8253. return Engine._ALPHA_COMBINE;
  8254. },
  8255. enumerable: true,
  8256. configurable: true
  8257. });
  8258. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8259. get: function () {
  8260. return Engine._ALPHA_SUBTRACT;
  8261. },
  8262. enumerable: true,
  8263. configurable: true
  8264. });
  8265. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8266. get: function () {
  8267. return Engine._ALPHA_MULTIPLY;
  8268. },
  8269. enumerable: true,
  8270. configurable: true
  8271. });
  8272. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8273. get: function () {
  8274. return Engine._ALPHA_MAXIMIZED;
  8275. },
  8276. enumerable: true,
  8277. configurable: true
  8278. });
  8279. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8280. get: function () {
  8281. return Engine._ALPHA_PREMULTIPLIED;
  8282. },
  8283. enumerable: true,
  8284. configurable: true
  8285. });
  8286. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8287. get: function () {
  8288. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8289. },
  8290. enumerable: true,
  8291. configurable: true
  8292. });
  8293. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8294. get: function () {
  8295. return Engine._ALPHA_INTERPOLATE;
  8296. },
  8297. enumerable: true,
  8298. configurable: true
  8299. });
  8300. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8301. get: function () {
  8302. return Engine._ALPHA_SCREENMODE;
  8303. },
  8304. enumerable: true,
  8305. configurable: true
  8306. });
  8307. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8308. get: function () {
  8309. return Engine._DELAYLOADSTATE_NONE;
  8310. },
  8311. enumerable: true,
  8312. configurable: true
  8313. });
  8314. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8315. get: function () {
  8316. return Engine._DELAYLOADSTATE_LOADED;
  8317. },
  8318. enumerable: true,
  8319. configurable: true
  8320. });
  8321. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8322. get: function () {
  8323. return Engine._DELAYLOADSTATE_LOADING;
  8324. },
  8325. enumerable: true,
  8326. configurable: true
  8327. });
  8328. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8329. get: function () {
  8330. return Engine._DELAYLOADSTATE_NOTLOADED;
  8331. },
  8332. enumerable: true,
  8333. configurable: true
  8334. });
  8335. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8336. get: function () {
  8337. return Engine._TEXTUREFORMAT_ALPHA;
  8338. },
  8339. enumerable: true,
  8340. configurable: true
  8341. });
  8342. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8343. get: function () {
  8344. return Engine._TEXTUREFORMAT_LUMINANCE;
  8345. },
  8346. enumerable: true,
  8347. configurable: true
  8348. });
  8349. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8350. get: function () {
  8351. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8352. },
  8353. enumerable: true,
  8354. configurable: true
  8355. });
  8356. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8357. get: function () {
  8358. return Engine._TEXTUREFORMAT_RGB;
  8359. },
  8360. enumerable: true,
  8361. configurable: true
  8362. });
  8363. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8364. get: function () {
  8365. return Engine._TEXTUREFORMAT_RGBA;
  8366. },
  8367. enumerable: true,
  8368. configurable: true
  8369. });
  8370. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8371. get: function () {
  8372. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8373. },
  8374. enumerable: true,
  8375. configurable: true
  8376. });
  8377. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8378. get: function () {
  8379. return Engine._TEXTURETYPE_FLOAT;
  8380. },
  8381. enumerable: true,
  8382. configurable: true
  8383. });
  8384. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8385. get: function () {
  8386. return Engine._TEXTURETYPE_HALF_FLOAT;
  8387. },
  8388. enumerable: true,
  8389. configurable: true
  8390. });
  8391. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8392. get: function () {
  8393. return Engine._SCALEMODE_FLOOR;
  8394. },
  8395. enumerable: true,
  8396. configurable: true
  8397. });
  8398. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8399. get: function () {
  8400. return Engine._SCALEMODE_NEAREST;
  8401. },
  8402. enumerable: true,
  8403. configurable: true
  8404. });
  8405. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8406. get: function () {
  8407. return Engine._SCALEMODE_CEILING;
  8408. },
  8409. enumerable: true,
  8410. configurable: true
  8411. });
  8412. Object.defineProperty(Engine, "Version", {
  8413. get: function () {
  8414. return "3.1-alpha";
  8415. },
  8416. enumerable: true,
  8417. configurable: true
  8418. });
  8419. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8420. get: function () {
  8421. return this._vrExclusivePointerMode;
  8422. },
  8423. enumerable: true,
  8424. configurable: true
  8425. });
  8426. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8427. get: function () {
  8428. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8429. },
  8430. enumerable: true,
  8431. configurable: true
  8432. });
  8433. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8434. get: function () {
  8435. return this._webGLVersion < 2 || this.forcePOTTextures;
  8436. },
  8437. enumerable: true,
  8438. configurable: true
  8439. });
  8440. Object.defineProperty(Engine.prototype, "badOS", {
  8441. get: function () {
  8442. return this._badOS;
  8443. },
  8444. enumerable: true,
  8445. configurable: true
  8446. });
  8447. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8448. get: function () {
  8449. return this._badDesktopOS;
  8450. },
  8451. enumerable: true,
  8452. configurable: true
  8453. });
  8454. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8455. get: function () {
  8456. return this._performanceMonitor;
  8457. },
  8458. enumerable: true,
  8459. configurable: true
  8460. });
  8461. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8462. get: function () {
  8463. return this._texturesSupported;
  8464. },
  8465. enumerable: true,
  8466. configurable: true
  8467. });
  8468. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8469. get: function () {
  8470. return this._textureFormatInUse;
  8471. },
  8472. enumerable: true,
  8473. configurable: true
  8474. });
  8475. Object.defineProperty(Engine.prototype, "currentViewport", {
  8476. get: function () {
  8477. return this._cachedViewport;
  8478. },
  8479. enumerable: true,
  8480. configurable: true
  8481. });
  8482. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8483. // Empty texture
  8484. get: function () {
  8485. if (!this._emptyTexture) {
  8486. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8487. }
  8488. return this._emptyTexture;
  8489. },
  8490. enumerable: true,
  8491. configurable: true
  8492. });
  8493. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8494. get: function () {
  8495. if (!this._emptyTexture3D) {
  8496. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8497. }
  8498. return this._emptyTexture3D;
  8499. },
  8500. enumerable: true,
  8501. configurable: true
  8502. });
  8503. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8504. get: function () {
  8505. if (!this._emptyCubeTexture) {
  8506. var faceData = new Uint8Array(4);
  8507. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8508. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8509. }
  8510. return this._emptyCubeTexture;
  8511. },
  8512. enumerable: true,
  8513. configurable: true
  8514. });
  8515. Engine.prototype._rebuildInternalTextures = function () {
  8516. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8517. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8518. var internalTexture = currentState_1[_i];
  8519. internalTexture._rebuild();
  8520. }
  8521. };
  8522. Engine.prototype._rebuildEffects = function () {
  8523. for (var key in this._compiledEffects) {
  8524. var effect = this._compiledEffects[key];
  8525. effect._prepareEffect();
  8526. }
  8527. BABYLON.Effect.ResetCache();
  8528. };
  8529. Engine.prototype._rebuildBuffers = function () {
  8530. // Index / Vertex
  8531. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8532. var scene = _a[_i];
  8533. scene.resetCachedMaterial();
  8534. scene._rebuildGeometries();
  8535. scene._rebuildTextures();
  8536. }
  8537. // Uniforms
  8538. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8539. var uniformBuffer = _c[_b];
  8540. uniformBuffer._rebuild();
  8541. }
  8542. };
  8543. Engine.prototype._initGLContext = function () {
  8544. // Caps
  8545. this._caps = new EngineCapabilities();
  8546. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8547. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8548. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8549. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8550. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8551. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8552. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8553. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8554. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8555. // Infos
  8556. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8557. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8558. if (rendererInfo != null) {
  8559. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8560. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8561. }
  8562. if (!this._glVendor) {
  8563. this._glVendor = "Unknown vendor";
  8564. }
  8565. if (!this._glRenderer) {
  8566. this._glRenderer = "Unknown renderer";
  8567. }
  8568. // Constants
  8569. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8570. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8571. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8572. this._gl.DEPTH24_STENCIL8 = 35056;
  8573. // Extensions
  8574. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8575. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8576. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8577. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8578. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8579. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8580. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8581. 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');
  8582. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8583. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8584. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8585. this._caps.highPrecisionShaderSupported = true;
  8586. // Checks if some of the format renders first to allow the use of webgl inspector.
  8587. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8588. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8589. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8590. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8591. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8592. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8593. if (this._webGLVersion > 1) {
  8594. this._gl.HALF_FLOAT_OES = 0x140B;
  8595. }
  8596. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8597. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8598. // Draw buffers
  8599. if (this._webGLVersion > 1) {
  8600. this._caps.drawBuffersExtension = true;
  8601. }
  8602. else {
  8603. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8604. if (drawBuffersExtension !== null) {
  8605. this._caps.drawBuffersExtension = true;
  8606. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8607. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8608. for (var i = 0; i < 16; i++) {
  8609. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8610. }
  8611. }
  8612. else {
  8613. this._caps.drawBuffersExtension = false;
  8614. }
  8615. }
  8616. // Depth Texture
  8617. if (this._webGLVersion > 1) {
  8618. this._caps.depthTextureExtension = true;
  8619. }
  8620. else {
  8621. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8622. if (depthTextureExtension != null) {
  8623. this._caps.depthTextureExtension = true;
  8624. }
  8625. }
  8626. // Vertex array object
  8627. if (this._webGLVersion > 1) {
  8628. this._caps.vertexArrayObject = true;
  8629. }
  8630. else {
  8631. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8632. if (vertexArrayObjectExtension != null) {
  8633. this._caps.vertexArrayObject = true;
  8634. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8635. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8636. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8637. }
  8638. else {
  8639. this._caps.vertexArrayObject = false;
  8640. }
  8641. }
  8642. // Instances count
  8643. if (this._webGLVersion > 1) {
  8644. this._caps.instancedArrays = true;
  8645. }
  8646. else {
  8647. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8648. if (instanceExtension != null) {
  8649. this._caps.instancedArrays = true;
  8650. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8651. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8652. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8653. }
  8654. else {
  8655. this._caps.instancedArrays = false;
  8656. }
  8657. }
  8658. // Intelligently add supported compressed formats in order to check for.
  8659. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8660. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8661. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8662. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8663. if (this._caps.astc)
  8664. this.texturesSupported.push('-astc.ktx');
  8665. if (this._caps.s3tc)
  8666. this.texturesSupported.push('-dxt.ktx');
  8667. if (this._caps.pvrtc)
  8668. this.texturesSupported.push('-pvrtc.ktx');
  8669. if (this._caps.etc2)
  8670. this.texturesSupported.push('-etc2.ktx');
  8671. if (this._caps.etc1)
  8672. this.texturesSupported.push('-etc1.ktx');
  8673. if (this._gl.getShaderPrecisionFormat) {
  8674. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8675. if (highp) {
  8676. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8677. }
  8678. }
  8679. // Depth buffer
  8680. this.setDepthBuffer(true);
  8681. this.setDepthFunctionToLessOrEqual();
  8682. this.setDepthWrite(true);
  8683. };
  8684. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8685. get: function () {
  8686. return this._webGLVersion;
  8687. },
  8688. enumerable: true,
  8689. configurable: true
  8690. });
  8691. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8692. /**
  8693. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8694. */
  8695. get: function () {
  8696. return this._isStencilEnable;
  8697. },
  8698. enumerable: true,
  8699. configurable: true
  8700. });
  8701. Engine.prototype._prepareWorkingCanvas = function () {
  8702. if (this._workingCanvas) {
  8703. return;
  8704. }
  8705. this._workingCanvas = document.createElement("canvas");
  8706. var context = this._workingCanvas.getContext("2d");
  8707. if (context) {
  8708. this._workingContext = context;
  8709. }
  8710. };
  8711. Engine.prototype.resetTextureCache = function () {
  8712. for (var key in this._activeTexturesCache) {
  8713. this._activeTexturesCache[key] = null;
  8714. }
  8715. };
  8716. Engine.prototype.isDeterministicLockStep = function () {
  8717. return this._deterministicLockstep;
  8718. };
  8719. Engine.prototype.getLockstepMaxSteps = function () {
  8720. return this._lockstepMaxSteps;
  8721. };
  8722. Engine.prototype.getGlInfo = function () {
  8723. return {
  8724. vendor: this._glVendor,
  8725. renderer: this._glRenderer,
  8726. version: this._glVersion
  8727. };
  8728. };
  8729. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8730. if (useScreen === void 0) { useScreen = false; }
  8731. var viewport = camera.viewport;
  8732. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8733. };
  8734. Engine.prototype.getRenderWidth = function (useScreen) {
  8735. if (useScreen === void 0) { useScreen = false; }
  8736. if (!useScreen && this._currentRenderTarget) {
  8737. return this._currentRenderTarget.width;
  8738. }
  8739. return this._gl.drawingBufferWidth;
  8740. };
  8741. Engine.prototype.getRenderHeight = function (useScreen) {
  8742. if (useScreen === void 0) { useScreen = false; }
  8743. if (!useScreen && this._currentRenderTarget) {
  8744. return this._currentRenderTarget.height;
  8745. }
  8746. return this._gl.drawingBufferHeight;
  8747. };
  8748. Engine.prototype.getRenderingCanvas = function () {
  8749. return this._renderingCanvas;
  8750. };
  8751. Engine.prototype.getRenderingCanvasClientRect = function () {
  8752. if (!this._renderingCanvas) {
  8753. return null;
  8754. }
  8755. return this._renderingCanvas.getBoundingClientRect();
  8756. };
  8757. Engine.prototype.setHardwareScalingLevel = function (level) {
  8758. this._hardwareScalingLevel = level;
  8759. this.resize();
  8760. };
  8761. Engine.prototype.getHardwareScalingLevel = function () {
  8762. return this._hardwareScalingLevel;
  8763. };
  8764. Engine.prototype.getLoadedTexturesCache = function () {
  8765. return this._internalTexturesCache;
  8766. };
  8767. Engine.prototype.getCaps = function () {
  8768. return this._caps;
  8769. };
  8770. Object.defineProperty(Engine.prototype, "drawCalls", {
  8771. /** The number of draw calls submitted last frame */
  8772. get: function () {
  8773. return this._drawCalls.current;
  8774. },
  8775. enumerable: true,
  8776. configurable: true
  8777. });
  8778. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8779. get: function () {
  8780. return this._drawCalls;
  8781. },
  8782. enumerable: true,
  8783. configurable: true
  8784. });
  8785. Engine.prototype.getDepthFunction = function () {
  8786. return this._depthCullingState.depthFunc;
  8787. };
  8788. Engine.prototype.setDepthFunction = function (depthFunc) {
  8789. this._depthCullingState.depthFunc = depthFunc;
  8790. };
  8791. Engine.prototype.setDepthFunctionToGreater = function () {
  8792. this._depthCullingState.depthFunc = this._gl.GREATER;
  8793. };
  8794. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8795. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8796. };
  8797. Engine.prototype.setDepthFunctionToLess = function () {
  8798. this._depthCullingState.depthFunc = this._gl.LESS;
  8799. };
  8800. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8801. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8802. };
  8803. Engine.prototype.getStencilBuffer = function () {
  8804. return this._stencilState.stencilTest;
  8805. };
  8806. Engine.prototype.setStencilBuffer = function (enable) {
  8807. this._stencilState.stencilTest = enable;
  8808. };
  8809. Engine.prototype.getStencilMask = function () {
  8810. return this._stencilState.stencilMask;
  8811. };
  8812. Engine.prototype.setStencilMask = function (mask) {
  8813. this._stencilState.stencilMask = mask;
  8814. };
  8815. Engine.prototype.getStencilFunction = function () {
  8816. return this._stencilState.stencilFunc;
  8817. };
  8818. Engine.prototype.getStencilFunctionReference = function () {
  8819. return this._stencilState.stencilFuncRef;
  8820. };
  8821. Engine.prototype.getStencilFunctionMask = function () {
  8822. return this._stencilState.stencilFuncMask;
  8823. };
  8824. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8825. this._stencilState.stencilFunc = stencilFunc;
  8826. };
  8827. Engine.prototype.setStencilFunctionReference = function (reference) {
  8828. this._stencilState.stencilFuncRef = reference;
  8829. };
  8830. Engine.prototype.setStencilFunctionMask = function (mask) {
  8831. this._stencilState.stencilFuncMask = mask;
  8832. };
  8833. Engine.prototype.getStencilOperationFail = function () {
  8834. return this._stencilState.stencilOpStencilFail;
  8835. };
  8836. Engine.prototype.getStencilOperationDepthFail = function () {
  8837. return this._stencilState.stencilOpDepthFail;
  8838. };
  8839. Engine.prototype.getStencilOperationPass = function () {
  8840. return this._stencilState.stencilOpStencilDepthPass;
  8841. };
  8842. Engine.prototype.setStencilOperationFail = function (operation) {
  8843. this._stencilState.stencilOpStencilFail = operation;
  8844. };
  8845. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8846. this._stencilState.stencilOpDepthFail = operation;
  8847. };
  8848. Engine.prototype.setStencilOperationPass = function (operation) {
  8849. this._stencilState.stencilOpStencilDepthPass = operation;
  8850. };
  8851. Engine.prototype.setDitheringState = function (value) {
  8852. if (value) {
  8853. this._gl.enable(this._gl.DITHER);
  8854. }
  8855. else {
  8856. this._gl.disable(this._gl.DITHER);
  8857. }
  8858. };
  8859. /**
  8860. * stop executing a render loop function and remove it from the execution array
  8861. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8862. */
  8863. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8864. if (!renderFunction) {
  8865. this._activeRenderLoops = [];
  8866. return;
  8867. }
  8868. var index = this._activeRenderLoops.indexOf(renderFunction);
  8869. if (index >= 0) {
  8870. this._activeRenderLoops.splice(index, 1);
  8871. }
  8872. };
  8873. Engine.prototype._renderLoop = function () {
  8874. if (!this._contextWasLost) {
  8875. var shouldRender = true;
  8876. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8877. shouldRender = false;
  8878. }
  8879. if (shouldRender) {
  8880. // Start new frame
  8881. this.beginFrame();
  8882. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8883. var renderFunction = this._activeRenderLoops[index];
  8884. renderFunction();
  8885. }
  8886. // Present
  8887. this.endFrame();
  8888. }
  8889. }
  8890. if (this._activeRenderLoops.length > 0) {
  8891. // Register new frame
  8892. var requester = null;
  8893. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8894. requester = this._vrDisplay;
  8895. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8896. }
  8897. else {
  8898. this._renderingQueueLaunched = false;
  8899. }
  8900. };
  8901. /**
  8902. * Register and execute a render loop. The engine can have more than one render function.
  8903. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8904. * @example
  8905. * engine.runRenderLoop(function () {
  8906. * scene.render()
  8907. * })
  8908. */
  8909. Engine.prototype.runRenderLoop = function (renderFunction) {
  8910. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8911. return;
  8912. }
  8913. this._activeRenderLoops.push(renderFunction);
  8914. if (!this._renderingQueueLaunched) {
  8915. this._renderingQueueLaunched = true;
  8916. this._bindedRenderFunction = this._renderLoop.bind(this);
  8917. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8918. }
  8919. };
  8920. /**
  8921. * Toggle full screen mode.
  8922. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8923. * @param {any} options - an options object to be sent to the requestFullscreen function
  8924. */
  8925. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8926. if (this.isFullscreen) {
  8927. BABYLON.Tools.ExitFullscreen();
  8928. }
  8929. else {
  8930. this._pointerLockRequested = requestPointerLock;
  8931. if (this._renderingCanvas) {
  8932. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8933. }
  8934. }
  8935. };
  8936. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8937. if (stencil === void 0) { stencil = false; }
  8938. this.applyStates();
  8939. var mode = 0;
  8940. if (backBuffer && color) {
  8941. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8942. mode |= this._gl.COLOR_BUFFER_BIT;
  8943. }
  8944. if (depth) {
  8945. this._gl.clearDepth(1.0);
  8946. mode |= this._gl.DEPTH_BUFFER_BIT;
  8947. }
  8948. if (stencil) {
  8949. this._gl.clearStencil(0);
  8950. mode |= this._gl.STENCIL_BUFFER_BIT;
  8951. }
  8952. this._gl.clear(mode);
  8953. };
  8954. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8955. var gl = this._gl;
  8956. // Save state
  8957. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8958. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8959. // Change state
  8960. gl.enable(gl.SCISSOR_TEST);
  8961. gl.scissor(x, y, width, height);
  8962. // Clear
  8963. this.clear(clearColor, true, true, true);
  8964. // Restore state
  8965. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8966. if (curScissor === true) {
  8967. gl.enable(gl.SCISSOR_TEST);
  8968. }
  8969. else {
  8970. gl.disable(gl.SCISSOR_TEST);
  8971. }
  8972. };
  8973. /**
  8974. * Set the WebGL's viewport
  8975. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8976. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8977. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8978. */
  8979. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8980. var width = requiredWidth || this.getRenderWidth();
  8981. var height = requiredHeight || this.getRenderHeight();
  8982. var x = viewport.x || 0;
  8983. var y = viewport.y || 0;
  8984. this._cachedViewport = viewport;
  8985. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8986. };
  8987. /**
  8988. * Directly set the WebGL Viewport
  8989. * The x, y, width & height are directly passed to the WebGL call
  8990. * @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.
  8991. */
  8992. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8993. var currentViewport = this._cachedViewport;
  8994. this._cachedViewport = null;
  8995. this._gl.viewport(x, y, width, height);
  8996. return currentViewport;
  8997. };
  8998. Engine.prototype.beginFrame = function () {
  8999. this._measureFps();
  9000. };
  9001. Engine.prototype.endFrame = function () {
  9002. //force a flush in case we are using a bad OS.
  9003. if (this._badOS) {
  9004. this.flushFramebuffer();
  9005. }
  9006. //submit frame to the vr device, if enabled
  9007. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9008. // TODO: We should only submit the frame if we read frameData successfully.
  9009. this._vrDisplay.submitFrame();
  9010. }
  9011. };
  9012. /**
  9013. * resize the view according to the canvas' size.
  9014. * @example
  9015. * window.addEventListener("resize", function () {
  9016. * engine.resize();
  9017. * });
  9018. */
  9019. Engine.prototype.resize = function () {
  9020. // We're not resizing the size of the canvas while in VR mode & presenting
  9021. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9022. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9023. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9024. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9025. }
  9026. };
  9027. /**
  9028. * force a specific size of the canvas
  9029. * @param {number} width - the new canvas' width
  9030. * @param {number} height - the new canvas' height
  9031. */
  9032. Engine.prototype.setSize = function (width, height) {
  9033. if (!this._renderingCanvas) {
  9034. return;
  9035. }
  9036. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9037. return;
  9038. }
  9039. this._renderingCanvas.width = width;
  9040. this._renderingCanvas.height = height;
  9041. for (var index = 0; index < this.scenes.length; index++) {
  9042. var scene = this.scenes[index];
  9043. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9044. var cam = scene.cameras[camIndex];
  9045. cam._currentRenderId = 0;
  9046. }
  9047. }
  9048. if (this.onResizeObservable.hasObservers) {
  9049. this.onResizeObservable.notifyObservers(this);
  9050. }
  9051. };
  9052. // WebVR functions
  9053. Engine.prototype.isVRDevicePresent = function () {
  9054. return !!this._vrDisplay;
  9055. };
  9056. Engine.prototype.getVRDevice = function () {
  9057. return this._vrDisplay;
  9058. };
  9059. Engine.prototype.initWebVR = function () {
  9060. var _this = this;
  9061. var notifyObservers = function () {
  9062. var eventArgs = {
  9063. vrDisplay: _this._vrDisplay,
  9064. vrSupported: _this._vrSupported
  9065. };
  9066. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9067. };
  9068. if (!this._onVrDisplayConnect) {
  9069. this._onVrDisplayConnect = function (event) {
  9070. _this._vrDisplay = event.display;
  9071. notifyObservers();
  9072. };
  9073. this._onVrDisplayDisconnect = function () {
  9074. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9075. _this._vrDisplay = undefined;
  9076. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9077. notifyObservers();
  9078. };
  9079. this._onVrDisplayPresentChange = function () {
  9080. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9081. };
  9082. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9083. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9084. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9085. }
  9086. this._getVRDisplays(notifyObservers);
  9087. return this.onVRDisplayChangedObservable;
  9088. };
  9089. Engine.prototype.enableVR = function () {
  9090. var _this = this;
  9091. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9092. var onResolved = function () {
  9093. _this.onVRRequestPresentComplete.notifyObservers(true);
  9094. _this._onVRFullScreenTriggered();
  9095. };
  9096. var onRejected = function () {
  9097. _this.onVRRequestPresentComplete.notifyObservers(false);
  9098. };
  9099. this.onVRRequestPresentStart.notifyObservers(this);
  9100. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9101. }
  9102. };
  9103. Engine.prototype.disableVR = function () {
  9104. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9105. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9106. }
  9107. };
  9108. Engine.prototype._getVRDisplays = function (callback) {
  9109. var _this = this;
  9110. var getWebVRDevices = function (devices) {
  9111. _this._vrSupported = true;
  9112. // note that devices may actually be an empty array. This is fine;
  9113. // we expect this._vrDisplay to be undefined in this case.
  9114. return _this._vrDisplay = devices[0];
  9115. };
  9116. if (navigator.getVRDisplays) {
  9117. // TODO: Backwards compatible for 1.0?
  9118. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9119. // TODO: System CANNOT support WebVR, despite API presence.
  9120. _this._vrSupported = false;
  9121. callback();
  9122. });
  9123. }
  9124. else {
  9125. // TODO: Browser does not support WebVR
  9126. this._vrDisplay = undefined;
  9127. this._vrSupported = false;
  9128. callback();
  9129. }
  9130. };
  9131. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9132. if (this._currentRenderTarget) {
  9133. this.unBindFramebuffer(this._currentRenderTarget);
  9134. }
  9135. this._currentRenderTarget = texture;
  9136. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9137. var gl = this._gl;
  9138. if (texture.isCube) {
  9139. if (faceIndex === undefined) {
  9140. faceIndex = 0;
  9141. }
  9142. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9143. }
  9144. if (this._cachedViewport && !forceFullscreenViewport) {
  9145. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9146. }
  9147. else {
  9148. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9149. }
  9150. this.wipeCaches();
  9151. };
  9152. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9153. if (this._currentFramebuffer !== framebuffer) {
  9154. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9155. this._currentFramebuffer = framebuffer;
  9156. }
  9157. };
  9158. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9159. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9160. this._currentRenderTarget = null;
  9161. // If MSAA, we need to bitblt back to main texture
  9162. var gl = this._gl;
  9163. if (texture._MSAAFramebuffer) {
  9164. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9165. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9166. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9167. }
  9168. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9169. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9170. gl.generateMipmap(gl.TEXTURE_2D);
  9171. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9172. }
  9173. if (onBeforeUnbind) {
  9174. if (texture._MSAAFramebuffer) {
  9175. // Bind the correct framebuffer
  9176. this.bindUnboundFramebuffer(texture._framebuffer);
  9177. }
  9178. onBeforeUnbind();
  9179. }
  9180. this.bindUnboundFramebuffer(null);
  9181. };
  9182. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9183. if (texture.generateMipMaps) {
  9184. var gl = this._gl;
  9185. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9186. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9187. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9188. }
  9189. };
  9190. Engine.prototype.flushFramebuffer = function () {
  9191. this._gl.flush();
  9192. };
  9193. Engine.prototype.restoreDefaultFramebuffer = function () {
  9194. if (this._currentRenderTarget) {
  9195. this.unBindFramebuffer(this._currentRenderTarget);
  9196. }
  9197. else {
  9198. this.bindUnboundFramebuffer(null);
  9199. }
  9200. if (this._cachedViewport) {
  9201. this.setViewport(this._cachedViewport);
  9202. }
  9203. this.wipeCaches();
  9204. };
  9205. // UBOs
  9206. Engine.prototype.createUniformBuffer = function (elements) {
  9207. var ubo = this._gl.createBuffer();
  9208. if (!ubo) {
  9209. throw new Error("Unable to create uniform buffer");
  9210. }
  9211. this.bindUniformBuffer(ubo);
  9212. if (elements instanceof Float32Array) {
  9213. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9214. }
  9215. else {
  9216. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9217. }
  9218. this.bindUniformBuffer(null);
  9219. ubo.references = 1;
  9220. return ubo;
  9221. };
  9222. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9223. var ubo = this._gl.createBuffer();
  9224. if (!ubo) {
  9225. throw new Error("Unable to create dynamic uniform buffer");
  9226. }
  9227. this.bindUniformBuffer(ubo);
  9228. if (elements instanceof Float32Array) {
  9229. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9230. }
  9231. else {
  9232. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9233. }
  9234. this.bindUniformBuffer(null);
  9235. ubo.references = 1;
  9236. return ubo;
  9237. };
  9238. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9239. this.bindUniformBuffer(uniformBuffer);
  9240. if (offset === undefined) {
  9241. offset = 0;
  9242. }
  9243. if (count === undefined) {
  9244. if (elements instanceof Float32Array) {
  9245. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9246. }
  9247. else {
  9248. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9249. }
  9250. }
  9251. else {
  9252. if (elements instanceof Float32Array) {
  9253. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9254. }
  9255. else {
  9256. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9257. }
  9258. }
  9259. this.bindUniformBuffer(null);
  9260. };
  9261. // VBOs
  9262. Engine.prototype._resetVertexBufferBinding = function () {
  9263. this.bindArrayBuffer(null);
  9264. this._cachedVertexBuffers = null;
  9265. };
  9266. Engine.prototype.createVertexBuffer = function (vertices) {
  9267. var vbo = this._gl.createBuffer();
  9268. if (!vbo) {
  9269. throw new Error("Unable to create vertex buffer");
  9270. }
  9271. this.bindArrayBuffer(vbo);
  9272. if (vertices instanceof Float32Array) {
  9273. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9274. }
  9275. else {
  9276. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9277. }
  9278. this._resetVertexBufferBinding();
  9279. vbo.references = 1;
  9280. return vbo;
  9281. };
  9282. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9283. var vbo = this._gl.createBuffer();
  9284. if (!vbo) {
  9285. throw new Error("Unable to create dynamic vertex buffer");
  9286. }
  9287. this.bindArrayBuffer(vbo);
  9288. if (vertices instanceof Float32Array) {
  9289. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9290. }
  9291. else {
  9292. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9293. }
  9294. this._resetVertexBufferBinding();
  9295. vbo.references = 1;
  9296. return vbo;
  9297. };
  9298. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9299. if (offset === void 0) { offset = 0; }
  9300. // Force cache update
  9301. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9302. this.bindIndexBuffer(indexBuffer);
  9303. var arrayBuffer;
  9304. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9305. arrayBuffer = indices;
  9306. }
  9307. else {
  9308. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9309. }
  9310. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9311. this._resetIndexBufferBinding();
  9312. };
  9313. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9314. this.bindArrayBuffer(vertexBuffer);
  9315. if (offset === undefined) {
  9316. offset = 0;
  9317. }
  9318. if (count === undefined) {
  9319. if (vertices instanceof Float32Array) {
  9320. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9321. }
  9322. else {
  9323. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9324. }
  9325. }
  9326. else {
  9327. if (vertices instanceof Float32Array) {
  9328. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9329. }
  9330. else {
  9331. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9332. }
  9333. }
  9334. this._resetVertexBufferBinding();
  9335. };
  9336. Engine.prototype._resetIndexBufferBinding = function () {
  9337. this.bindIndexBuffer(null);
  9338. this._cachedIndexBuffer = null;
  9339. };
  9340. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9341. var vbo = this._gl.createBuffer();
  9342. if (!vbo) {
  9343. throw new Error("Unable to create index buffer");
  9344. }
  9345. this.bindIndexBuffer(vbo);
  9346. // Check for 32 bits indices
  9347. var arrayBuffer;
  9348. var need32Bits = false;
  9349. if (indices instanceof Uint16Array) {
  9350. arrayBuffer = indices;
  9351. }
  9352. else {
  9353. //check 32 bit support
  9354. if (this._caps.uintIndices) {
  9355. if (indices instanceof Uint32Array) {
  9356. arrayBuffer = indices;
  9357. need32Bits = true;
  9358. }
  9359. else {
  9360. //number[] or Int32Array, check if 32 bit is necessary
  9361. for (var index = 0; index < indices.length; index++) {
  9362. if (indices[index] > 65535) {
  9363. need32Bits = true;
  9364. break;
  9365. }
  9366. }
  9367. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9368. }
  9369. }
  9370. else {
  9371. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9372. arrayBuffer = new Uint16Array(indices);
  9373. }
  9374. }
  9375. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9376. this._resetIndexBufferBinding();
  9377. vbo.references = 1;
  9378. vbo.is32Bits = need32Bits;
  9379. return vbo;
  9380. };
  9381. Engine.prototype.bindArrayBuffer = function (buffer) {
  9382. if (!this._vaoRecordInProgress) {
  9383. this._unbindVertexArrayObject();
  9384. }
  9385. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9386. };
  9387. Engine.prototype.bindUniformBuffer = function (buffer) {
  9388. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9389. };
  9390. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9391. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9392. };
  9393. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9394. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9395. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9396. };
  9397. ;
  9398. Engine.prototype.bindIndexBuffer = function (buffer) {
  9399. if (!this._vaoRecordInProgress) {
  9400. this._unbindVertexArrayObject();
  9401. }
  9402. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9403. };
  9404. Engine.prototype.bindBuffer = function (buffer, target) {
  9405. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9406. this._gl.bindBuffer(target, buffer);
  9407. this._currentBoundBuffer[target] = buffer;
  9408. }
  9409. };
  9410. Engine.prototype.updateArrayBuffer = function (data) {
  9411. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9412. };
  9413. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9414. var pointer = this._currentBufferPointers[indx];
  9415. var changed = false;
  9416. if (!pointer.active) {
  9417. changed = true;
  9418. pointer.active = true;
  9419. pointer.index = indx;
  9420. pointer.size = size;
  9421. pointer.type = type;
  9422. pointer.normalized = normalized;
  9423. pointer.stride = stride;
  9424. pointer.offset = offset;
  9425. pointer.buffer = buffer;
  9426. }
  9427. else {
  9428. if (pointer.buffer !== buffer) {
  9429. pointer.buffer = buffer;
  9430. changed = true;
  9431. }
  9432. if (pointer.size !== size) {
  9433. pointer.size = size;
  9434. changed = true;
  9435. }
  9436. if (pointer.type !== type) {
  9437. pointer.type = type;
  9438. changed = true;
  9439. }
  9440. if (pointer.normalized !== normalized) {
  9441. pointer.normalized = normalized;
  9442. changed = true;
  9443. }
  9444. if (pointer.stride !== stride) {
  9445. pointer.stride = stride;
  9446. changed = true;
  9447. }
  9448. if (pointer.offset !== offset) {
  9449. pointer.offset = offset;
  9450. changed = true;
  9451. }
  9452. }
  9453. if (changed || this._vaoRecordInProgress) {
  9454. this.bindArrayBuffer(buffer);
  9455. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9456. }
  9457. };
  9458. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9459. if (indexBuffer == null) {
  9460. return;
  9461. }
  9462. if (this._cachedIndexBuffer !== indexBuffer) {
  9463. this._cachedIndexBuffer = indexBuffer;
  9464. this.bindIndexBuffer(indexBuffer);
  9465. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9466. }
  9467. };
  9468. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9469. var attributes = effect.getAttributesNames();
  9470. if (!this._vaoRecordInProgress) {
  9471. this._unbindVertexArrayObject();
  9472. }
  9473. this.unbindAllAttributes();
  9474. for (var index = 0; index < attributes.length; index++) {
  9475. var order = effect.getAttributeLocation(index);
  9476. if (order >= 0) {
  9477. var vertexBuffer = vertexBuffers[attributes[index]];
  9478. if (!vertexBuffer) {
  9479. continue;
  9480. }
  9481. this._gl.enableVertexAttribArray(order);
  9482. if (!this._vaoRecordInProgress) {
  9483. this._vertexAttribArraysEnabled[order] = true;
  9484. }
  9485. var buffer = vertexBuffer.getBuffer();
  9486. if (buffer) {
  9487. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9488. if (vertexBuffer.getIsInstanced()) {
  9489. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9490. if (!this._vaoRecordInProgress) {
  9491. this._currentInstanceLocations.push(order);
  9492. this._currentInstanceBuffers.push(buffer);
  9493. }
  9494. }
  9495. }
  9496. }
  9497. }
  9498. };
  9499. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9500. var vao = this._gl.createVertexArray();
  9501. this._vaoRecordInProgress = true;
  9502. this._gl.bindVertexArray(vao);
  9503. this._mustWipeVertexAttributes = true;
  9504. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9505. this.bindIndexBuffer(indexBuffer);
  9506. this._vaoRecordInProgress = false;
  9507. this._gl.bindVertexArray(null);
  9508. return vao;
  9509. };
  9510. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9511. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9512. this._cachedVertexArrayObject = vertexArrayObject;
  9513. this._gl.bindVertexArray(vertexArrayObject);
  9514. this._cachedVertexBuffers = null;
  9515. this._cachedIndexBuffer = null;
  9516. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9517. this._mustWipeVertexAttributes = true;
  9518. }
  9519. };
  9520. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9521. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9522. this._cachedVertexBuffers = vertexBuffer;
  9523. this._cachedEffectForVertexBuffers = effect;
  9524. var attributesCount = effect.getAttributesCount();
  9525. this._unbindVertexArrayObject();
  9526. this.unbindAllAttributes();
  9527. var offset = 0;
  9528. for (var index = 0; index < attributesCount; index++) {
  9529. if (index < vertexDeclaration.length) {
  9530. var order = effect.getAttributeLocation(index);
  9531. if (order >= 0) {
  9532. this._gl.enableVertexAttribArray(order);
  9533. this._vertexAttribArraysEnabled[order] = true;
  9534. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9535. }
  9536. offset += vertexDeclaration[index] * 4;
  9537. }
  9538. }
  9539. }
  9540. this._bindIndexBufferWithCache(indexBuffer);
  9541. };
  9542. Engine.prototype._unbindVertexArrayObject = function () {
  9543. if (!this._cachedVertexArrayObject) {
  9544. return;
  9545. }
  9546. this._cachedVertexArrayObject = null;
  9547. this._gl.bindVertexArray(null);
  9548. };
  9549. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9550. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9551. this._cachedVertexBuffers = vertexBuffers;
  9552. this._cachedEffectForVertexBuffers = effect;
  9553. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9554. }
  9555. this._bindIndexBufferWithCache(indexBuffer);
  9556. };
  9557. Engine.prototype.unbindInstanceAttributes = function () {
  9558. var boundBuffer;
  9559. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9560. var instancesBuffer = this._currentInstanceBuffers[i];
  9561. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9562. boundBuffer = instancesBuffer;
  9563. this.bindArrayBuffer(instancesBuffer);
  9564. }
  9565. var offsetLocation = this._currentInstanceLocations[i];
  9566. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9567. }
  9568. this._currentInstanceBuffers.length = 0;
  9569. this._currentInstanceLocations.length = 0;
  9570. };
  9571. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9572. this._gl.deleteVertexArray(vao);
  9573. };
  9574. Engine.prototype._releaseBuffer = function (buffer) {
  9575. buffer.references--;
  9576. if (buffer.references === 0) {
  9577. this._gl.deleteBuffer(buffer);
  9578. return true;
  9579. }
  9580. return false;
  9581. };
  9582. Engine.prototype.createInstancesBuffer = function (capacity) {
  9583. var buffer = this._gl.createBuffer();
  9584. if (!buffer) {
  9585. throw new Error("Unable to create instance buffer");
  9586. }
  9587. buffer.capacity = capacity;
  9588. this.bindArrayBuffer(buffer);
  9589. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9590. return buffer;
  9591. };
  9592. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9593. this._gl.deleteBuffer(buffer);
  9594. };
  9595. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9596. this.bindArrayBuffer(instancesBuffer);
  9597. if (data) {
  9598. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9599. }
  9600. if (offsetLocations[0].index !== undefined) {
  9601. var stride = 0;
  9602. for (var i = 0; i < offsetLocations.length; i++) {
  9603. var ai = offsetLocations[i];
  9604. stride += ai.attributeSize * 4;
  9605. }
  9606. for (var i = 0; i < offsetLocations.length; i++) {
  9607. var ai = offsetLocations[i];
  9608. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9609. this._gl.enableVertexAttribArray(ai.index);
  9610. this._vertexAttribArraysEnabled[ai.index] = true;
  9611. }
  9612. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9613. this._gl.vertexAttribDivisor(ai.index, 1);
  9614. this._currentInstanceLocations.push(ai.index);
  9615. this._currentInstanceBuffers.push(instancesBuffer);
  9616. }
  9617. }
  9618. else {
  9619. for (var index = 0; index < 4; index++) {
  9620. var offsetLocation = offsetLocations[index];
  9621. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9622. this._gl.enableVertexAttribArray(offsetLocation);
  9623. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9624. }
  9625. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9626. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9627. this._currentInstanceLocations.push(offsetLocation);
  9628. this._currentInstanceBuffers.push(instancesBuffer);
  9629. }
  9630. }
  9631. };
  9632. Engine.prototype.applyStates = function () {
  9633. this._depthCullingState.apply(this._gl);
  9634. this._stencilState.apply(this._gl);
  9635. this._alphaState.apply(this._gl);
  9636. };
  9637. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9638. // Apply states
  9639. this.applyStates();
  9640. this._drawCalls.addCount(1, false);
  9641. // Render
  9642. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9643. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9644. if (instancesCount) {
  9645. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9646. return;
  9647. }
  9648. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9649. };
  9650. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9651. // Apply states
  9652. this.applyStates();
  9653. this._drawCalls.addCount(1, false);
  9654. if (instancesCount) {
  9655. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9656. return;
  9657. }
  9658. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9659. };
  9660. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9661. // Apply states
  9662. this.applyStates();
  9663. this._drawCalls.addCount(1, false);
  9664. if (instancesCount) {
  9665. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9666. return;
  9667. }
  9668. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9669. };
  9670. // Shaders
  9671. Engine.prototype._releaseEffect = function (effect) {
  9672. if (this._compiledEffects[effect._key]) {
  9673. delete this._compiledEffects[effect._key];
  9674. this._deleteProgram(effect.getProgram());
  9675. }
  9676. };
  9677. Engine.prototype._deleteProgram = function (program) {
  9678. if (program) {
  9679. program.__SPECTOR_rebuildProgram = null;
  9680. this._gl.deleteProgram(program);
  9681. }
  9682. };
  9683. /**
  9684. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9685. * @param samplers An array of string used to represent textures
  9686. */
  9687. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9688. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9689. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9690. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9691. if (this._compiledEffects[name]) {
  9692. var compiledEffect = this._compiledEffects[name];
  9693. if (onCompiled && compiledEffect.isReady()) {
  9694. onCompiled(compiledEffect);
  9695. }
  9696. return compiledEffect;
  9697. }
  9698. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9699. effect._key = name;
  9700. this._compiledEffects[name] = effect;
  9701. return effect;
  9702. };
  9703. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9704. if (uniformsNames === void 0) { uniformsNames = []; }
  9705. if (samplers === void 0) { samplers = []; }
  9706. if (defines === void 0) { defines = ""; }
  9707. return this.createEffect({
  9708. vertex: "particles",
  9709. fragmentElement: fragmentName
  9710. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9711. };
  9712. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context) {
  9713. context = context || this._gl;
  9714. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9715. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9716. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9717. };
  9718. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9719. context = context || this._gl;
  9720. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9721. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9722. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9723. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9724. };
  9725. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context) {
  9726. var shaderProgram = context.createProgram();
  9727. if (!shaderProgram) {
  9728. throw new Error("Unable to create program");
  9729. }
  9730. context.attachShader(shaderProgram, vertexShader);
  9731. context.attachShader(shaderProgram, fragmentShader);
  9732. context.linkProgram(shaderProgram);
  9733. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9734. if (!linked) {
  9735. context.validateProgram(shaderProgram);
  9736. var error = context.getProgramInfoLog(shaderProgram);
  9737. if (error) {
  9738. throw new Error(error);
  9739. }
  9740. }
  9741. context.deleteShader(vertexShader);
  9742. context.deleteShader(fragmentShader);
  9743. return shaderProgram;
  9744. };
  9745. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9746. var results = new Array();
  9747. for (var index = 0; index < uniformsNames.length; index++) {
  9748. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9749. }
  9750. return results;
  9751. };
  9752. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9753. var results = [];
  9754. for (var index = 0; index < attributesNames.length; index++) {
  9755. try {
  9756. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9757. }
  9758. catch (e) {
  9759. results.push(-1);
  9760. }
  9761. }
  9762. return results;
  9763. };
  9764. Engine.prototype.enableEffect = function (effect) {
  9765. if (!effect) {
  9766. return;
  9767. }
  9768. // Use program
  9769. this.setProgram(effect.getProgram());
  9770. this._currentEffect = effect;
  9771. if (effect.onBind) {
  9772. effect.onBind(effect);
  9773. }
  9774. effect.onBindObservable.notifyObservers(effect);
  9775. };
  9776. Engine.prototype.setIntArray = function (uniform, array) {
  9777. if (!uniform)
  9778. return;
  9779. this._gl.uniform1iv(uniform, array);
  9780. };
  9781. Engine.prototype.setIntArray2 = function (uniform, array) {
  9782. if (!uniform || array.length % 2 !== 0)
  9783. return;
  9784. this._gl.uniform2iv(uniform, array);
  9785. };
  9786. Engine.prototype.setIntArray3 = function (uniform, array) {
  9787. if (!uniform || array.length % 3 !== 0)
  9788. return;
  9789. this._gl.uniform3iv(uniform, array);
  9790. };
  9791. Engine.prototype.setIntArray4 = function (uniform, array) {
  9792. if (!uniform || array.length % 4 !== 0)
  9793. return;
  9794. this._gl.uniform4iv(uniform, array);
  9795. };
  9796. Engine.prototype.setFloatArray = function (uniform, array) {
  9797. if (!uniform)
  9798. return;
  9799. this._gl.uniform1fv(uniform, array);
  9800. };
  9801. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9802. if (!uniform || array.length % 2 !== 0)
  9803. return;
  9804. this._gl.uniform2fv(uniform, array);
  9805. };
  9806. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9807. if (!uniform || array.length % 3 !== 0)
  9808. return;
  9809. this._gl.uniform3fv(uniform, array);
  9810. };
  9811. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9812. if (!uniform || array.length % 4 !== 0)
  9813. return;
  9814. this._gl.uniform4fv(uniform, array);
  9815. };
  9816. Engine.prototype.setArray = function (uniform, array) {
  9817. if (!uniform)
  9818. return;
  9819. this._gl.uniform1fv(uniform, array);
  9820. };
  9821. Engine.prototype.setArray2 = function (uniform, array) {
  9822. if (!uniform || array.length % 2 !== 0)
  9823. return;
  9824. this._gl.uniform2fv(uniform, array);
  9825. };
  9826. Engine.prototype.setArray3 = function (uniform, array) {
  9827. if (!uniform || array.length % 3 !== 0)
  9828. return;
  9829. this._gl.uniform3fv(uniform, array);
  9830. };
  9831. Engine.prototype.setArray4 = function (uniform, array) {
  9832. if (!uniform || array.length % 4 !== 0)
  9833. return;
  9834. this._gl.uniform4fv(uniform, array);
  9835. };
  9836. Engine.prototype.setMatrices = function (uniform, matrices) {
  9837. if (!uniform)
  9838. return;
  9839. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9840. };
  9841. Engine.prototype.setMatrix = function (uniform, matrix) {
  9842. if (!uniform)
  9843. return;
  9844. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9845. };
  9846. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9847. if (!uniform)
  9848. return;
  9849. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9850. };
  9851. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9852. if (!uniform)
  9853. return;
  9854. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9855. };
  9856. Engine.prototype.setFloat = function (uniform, value) {
  9857. if (!uniform)
  9858. return;
  9859. this._gl.uniform1f(uniform, value);
  9860. };
  9861. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9862. if (!uniform)
  9863. return;
  9864. this._gl.uniform2f(uniform, x, y);
  9865. };
  9866. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9867. if (!uniform)
  9868. return;
  9869. this._gl.uniform3f(uniform, x, y, z);
  9870. };
  9871. Engine.prototype.setBool = function (uniform, bool) {
  9872. if (!uniform)
  9873. return;
  9874. this._gl.uniform1i(uniform, bool);
  9875. };
  9876. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9877. if (!uniform)
  9878. return;
  9879. this._gl.uniform4f(uniform, x, y, z, w);
  9880. };
  9881. Engine.prototype.setColor3 = function (uniform, color3) {
  9882. if (!uniform)
  9883. return;
  9884. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9885. };
  9886. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9887. if (!uniform)
  9888. return;
  9889. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9890. };
  9891. // States
  9892. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9893. if (zOffset === void 0) { zOffset = 0; }
  9894. if (reverseSide === void 0) { reverseSide = false; }
  9895. // Culling
  9896. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9897. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9898. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9899. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9900. if (culling) {
  9901. this._depthCullingState.cullFace = cullFace;
  9902. this._depthCullingState.cull = true;
  9903. }
  9904. else {
  9905. this._depthCullingState.cull = false;
  9906. }
  9907. }
  9908. // Z offset
  9909. this.setZOffset(zOffset);
  9910. };
  9911. Engine.prototype.setZOffset = function (value) {
  9912. this._depthCullingState.zOffset = value;
  9913. };
  9914. Engine.prototype.getZOffset = function () {
  9915. return this._depthCullingState.zOffset;
  9916. };
  9917. Engine.prototype.setDepthBuffer = function (enable) {
  9918. this._depthCullingState.depthTest = enable;
  9919. };
  9920. Engine.prototype.getDepthWrite = function () {
  9921. return this._depthCullingState.depthMask;
  9922. };
  9923. Engine.prototype.setDepthWrite = function (enable) {
  9924. this._depthCullingState.depthMask = enable;
  9925. };
  9926. Engine.prototype.setColorWrite = function (enable) {
  9927. this._gl.colorMask(enable, enable, enable, enable);
  9928. this._colorWrite = enable;
  9929. };
  9930. Engine.prototype.getColorWrite = function () {
  9931. return this._colorWrite;
  9932. };
  9933. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9934. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9935. };
  9936. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9937. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9938. if (this._alphaMode === mode) {
  9939. return;
  9940. }
  9941. switch (mode) {
  9942. case Engine.ALPHA_DISABLE:
  9943. this._alphaState.alphaBlend = false;
  9944. break;
  9945. case Engine.ALPHA_PREMULTIPLIED:
  9946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9947. this._alphaState.alphaBlend = true;
  9948. break;
  9949. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9951. this._alphaState.alphaBlend = true;
  9952. break;
  9953. case Engine.ALPHA_COMBINE:
  9954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9955. this._alphaState.alphaBlend = true;
  9956. break;
  9957. case Engine.ALPHA_ONEONE:
  9958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9959. this._alphaState.alphaBlend = true;
  9960. break;
  9961. case Engine.ALPHA_ADD:
  9962. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9963. this._alphaState.alphaBlend = true;
  9964. break;
  9965. case Engine.ALPHA_SUBTRACT:
  9966. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9967. this._alphaState.alphaBlend = true;
  9968. break;
  9969. case Engine.ALPHA_MULTIPLY:
  9970. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9971. this._alphaState.alphaBlend = true;
  9972. break;
  9973. case Engine.ALPHA_MAXIMIZED:
  9974. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9975. this._alphaState.alphaBlend = true;
  9976. break;
  9977. case Engine.ALPHA_INTERPOLATE:
  9978. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9979. this._alphaState.alphaBlend = true;
  9980. break;
  9981. case Engine.ALPHA_SCREENMODE:
  9982. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9983. this._alphaState.alphaBlend = true;
  9984. break;
  9985. }
  9986. if (!noDepthWriteChange) {
  9987. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9988. }
  9989. this._alphaMode = mode;
  9990. };
  9991. Engine.prototype.getAlphaMode = function () {
  9992. return this._alphaMode;
  9993. };
  9994. Engine.prototype.setAlphaTesting = function (enable) {
  9995. this._alphaTest = enable;
  9996. };
  9997. Engine.prototype.getAlphaTesting = function () {
  9998. return !!this._alphaTest;
  9999. };
  10000. // Textures
  10001. Engine.prototype.wipeCaches = function (bruteForce) {
  10002. if (this.preventCacheWipeBetweenFrames) {
  10003. return;
  10004. }
  10005. this.resetTextureCache();
  10006. this._currentEffect = null;
  10007. // 6/8/2017: deltakosh: Should not be required anymore.
  10008. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10009. if (bruteForce) {
  10010. this._currentProgram = null;
  10011. this._stencilState.reset();
  10012. this._depthCullingState.reset();
  10013. this.setDepthFunctionToLessOrEqual();
  10014. this._alphaState.reset();
  10015. }
  10016. this._cachedVertexBuffers = null;
  10017. this._cachedIndexBuffer = null;
  10018. this._cachedEffectForVertexBuffers = null;
  10019. this._unbindVertexArrayObject();
  10020. this.bindIndexBuffer(null);
  10021. this.bindArrayBuffer(null);
  10022. };
  10023. /**
  10024. * Set the compressed texture format to use, based on the formats you have, and the formats
  10025. * supported by the hardware / browser.
  10026. *
  10027. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10028. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10029. * to API arguments needed to compressed textures. This puts the burden on the container
  10030. * generator to house the arcane code for determining these for current & future formats.
  10031. *
  10032. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10033. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10034. *
  10035. * Note: The result of this call is not taken into account when a texture is base64.
  10036. *
  10037. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10038. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10039. *
  10040. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10041. * @returns The extension selected.
  10042. */
  10043. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10044. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10045. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10046. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10047. return this._textureFormatInUse = this._texturesSupported[i];
  10048. }
  10049. }
  10050. }
  10051. // actively set format to nothing, to allow this to be called more than once
  10052. // and possibly fail the 2nd time
  10053. this._textureFormatInUse = null;
  10054. return null;
  10055. };
  10056. Engine.prototype._createTexture = function () {
  10057. var texture = this._gl.createTexture();
  10058. if (!texture) {
  10059. throw new Error("Unable to create texture");
  10060. }
  10061. return texture;
  10062. };
  10063. /**
  10064. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10065. * @param {string} urlArg- This contains one of the following:
  10066. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10067. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10068. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10069. *
  10070. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10071. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10072. * @param {Scene} scene- Needed for loading to the correct scene.
  10073. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10074. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10075. * @param {callback} onError- Optional callback to be called upon failure.
  10076. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10077. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10078. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10079. *
  10080. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10081. */
  10082. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10083. var _this = this;
  10084. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10085. if (onLoad === void 0) { onLoad = null; }
  10086. if (onError === void 0) { onError = null; }
  10087. if (buffer === void 0) { buffer = null; }
  10088. if (fallBack === void 0) { fallBack = null; }
  10089. if (format === void 0) { format = null; }
  10090. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10091. var fromData = url.substr(0, 5) === "data:";
  10092. var fromBlob = url.substr(0, 5) === "blob:";
  10093. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10094. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10095. // establish the file extension, if possible
  10096. var lastDot = url.lastIndexOf('.');
  10097. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10098. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10099. var isTGA = (extension === ".tga");
  10100. // determine if a ktx file should be substituted
  10101. var isKTX = false;
  10102. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10103. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10104. isKTX = true;
  10105. }
  10106. if (scene) {
  10107. scene._addPendingData(texture);
  10108. }
  10109. texture.url = url;
  10110. texture.generateMipMaps = !noMipmap;
  10111. texture.samplingMode = samplingMode;
  10112. texture.invertY = invertY;
  10113. if (!this._doNotHandleContextLost) {
  10114. // Keep a link to the buffer only if we plan to handle context lost
  10115. texture._buffer = buffer;
  10116. }
  10117. if (onLoad) {
  10118. texture.onLoadedObservable.add(onLoad);
  10119. }
  10120. if (!fallBack)
  10121. this._internalTexturesCache.push(texture);
  10122. var onerror = function () {
  10123. if (scene) {
  10124. scene._removePendingData(texture);
  10125. }
  10126. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10127. if (isKTX) {
  10128. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10129. }
  10130. else if (onError) {
  10131. onError();
  10132. }
  10133. };
  10134. var callback = null;
  10135. // processing for non-image formats
  10136. if (isKTX || isTGA || isDDS) {
  10137. if (isKTX) {
  10138. callback = function (data) {
  10139. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10140. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10141. ktx.uploadLevels(_this._gl, !noMipmap);
  10142. return false;
  10143. }, samplingMode);
  10144. };
  10145. }
  10146. else if (isTGA) {
  10147. callback = function (arrayBuffer) {
  10148. var data = new Uint8Array(arrayBuffer);
  10149. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10150. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10151. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10152. return false;
  10153. }, samplingMode);
  10154. };
  10155. }
  10156. else if (isDDS) {
  10157. callback = function (data) {
  10158. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10159. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10160. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10161. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10162. return false;
  10163. }, samplingMode);
  10164. };
  10165. }
  10166. if (!buffer) {
  10167. BABYLON.Tools.LoadFile(url, function (data) {
  10168. if (callback) {
  10169. callback(data);
  10170. }
  10171. }, undefined, scene ? scene.database : undefined, true, onerror);
  10172. }
  10173. else {
  10174. if (callback) {
  10175. callback(buffer);
  10176. }
  10177. }
  10178. // image format processing
  10179. }
  10180. else {
  10181. var onload = function (img) {
  10182. if (fromBlob && !_this._doNotHandleContextLost) {
  10183. // We need to store the image if we need to rebuild the texture
  10184. // in case of a webgl context lost
  10185. texture._buffer = img;
  10186. }
  10187. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10188. var gl = _this._gl;
  10189. var isPot = (img.width === potWidth && img.height === potHeight);
  10190. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10191. if (isPot) {
  10192. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10193. return false;
  10194. }
  10195. // Using shaders to rescale because canvas.drawImage is lossy
  10196. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10197. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10198. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10202. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10203. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10204. _this._releaseTexture(source);
  10205. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10206. continuationCallback();
  10207. });
  10208. return true;
  10209. }, samplingMode);
  10210. };
  10211. if (!fromData || isBase64)
  10212. if (buffer instanceof HTMLImageElement) {
  10213. onload(buffer);
  10214. }
  10215. else {
  10216. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10217. }
  10218. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10219. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10220. else
  10221. onload(buffer);
  10222. }
  10223. return texture;
  10224. };
  10225. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10226. var _this = this;
  10227. var rtt = this.createRenderTargetTexture({
  10228. width: destination.width,
  10229. height: destination.height,
  10230. }, {
  10231. generateMipMaps: false,
  10232. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10233. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10234. generateDepthBuffer: false,
  10235. generateStencilBuffer: false
  10236. });
  10237. if (!this._rescalePostProcess) {
  10238. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10239. }
  10240. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10241. _this._rescalePostProcess.onApply = function (effect) {
  10242. effect._bindTexture("textureSampler", source);
  10243. };
  10244. var hostingScene = scene;
  10245. if (!hostingScene) {
  10246. hostingScene = _this.scenes[_this.scenes.length - 1];
  10247. }
  10248. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10249. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10250. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10251. _this.unBindFramebuffer(rtt);
  10252. _this._releaseTexture(rtt);
  10253. if (onComplete) {
  10254. onComplete();
  10255. }
  10256. });
  10257. };
  10258. Engine.prototype._getInternalFormat = function (format) {
  10259. var internalFormat = this._gl.RGBA;
  10260. switch (format) {
  10261. case Engine.TEXTUREFORMAT_ALPHA:
  10262. internalFormat = this._gl.ALPHA;
  10263. break;
  10264. case Engine.TEXTUREFORMAT_LUMINANCE:
  10265. internalFormat = this._gl.LUMINANCE;
  10266. break;
  10267. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10268. internalFormat = this._gl.LUMINANCE_ALPHA;
  10269. break;
  10270. case Engine.TEXTUREFORMAT_RGB:
  10271. internalFormat = this._gl.RGB;
  10272. break;
  10273. case Engine.TEXTUREFORMAT_RGBA:
  10274. internalFormat = this._gl.RGBA;
  10275. break;
  10276. }
  10277. return internalFormat;
  10278. };
  10279. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10280. if (compression === void 0) { compression = null; }
  10281. if (!texture) {
  10282. return;
  10283. }
  10284. var internalFormat = this._getInternalFormat(format);
  10285. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10286. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10287. if (!this._doNotHandleContextLost) {
  10288. texture._bufferView = data;
  10289. texture.format = format;
  10290. texture.invertY = invertY;
  10291. texture._compression = compression;
  10292. }
  10293. if (texture.width % 4 !== 0) {
  10294. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10295. }
  10296. if (compression && data) {
  10297. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10298. }
  10299. else {
  10300. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10301. }
  10302. if (texture.generateMipMaps) {
  10303. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10304. }
  10305. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10306. this.resetTextureCache();
  10307. texture.isReady = true;
  10308. };
  10309. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10310. if (compression === void 0) { compression = null; }
  10311. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10312. texture.baseWidth = width;
  10313. texture.baseHeight = height;
  10314. texture.width = width;
  10315. texture.height = height;
  10316. texture.format = format;
  10317. texture.generateMipMaps = generateMipMaps;
  10318. texture.samplingMode = samplingMode;
  10319. texture.invertY = invertY;
  10320. texture._compression = compression;
  10321. if (!this._doNotHandleContextLost) {
  10322. texture._bufferView = data;
  10323. }
  10324. this.updateRawTexture(texture, data, format, invertY, compression);
  10325. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10326. // Filters
  10327. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10328. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10329. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10330. if (generateMipMaps) {
  10331. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10332. }
  10333. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10334. this._internalTexturesCache.push(texture);
  10335. return texture;
  10336. };
  10337. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10338. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10339. texture.baseWidth = width;
  10340. texture.baseHeight = height;
  10341. if (generateMipMaps) {
  10342. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10343. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10344. }
  10345. this.resetTextureCache();
  10346. texture.width = width;
  10347. texture.height = height;
  10348. texture.isReady = false;
  10349. texture.generateMipMaps = generateMipMaps;
  10350. texture.samplingMode = samplingMode;
  10351. this.updateTextureSamplingMode(samplingMode, texture);
  10352. this._internalTexturesCache.push(texture);
  10353. return texture;
  10354. };
  10355. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10356. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10357. if (texture.isCube) {
  10358. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10359. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10360. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10361. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10362. }
  10363. else if (texture.is3D) {
  10364. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10365. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10366. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10367. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10368. }
  10369. else {
  10370. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10371. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10372. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10373. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10374. }
  10375. texture.samplingMode = samplingMode;
  10376. };
  10377. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10378. if (premulAlpha === void 0) { premulAlpha = false; }
  10379. if (!texture) {
  10380. return;
  10381. }
  10382. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10383. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10384. if (premulAlpha) {
  10385. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10386. }
  10387. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10388. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10389. if (texture.generateMipMaps) {
  10390. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10391. }
  10392. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10393. if (premulAlpha) {
  10394. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10395. }
  10396. this.resetTextureCache();
  10397. texture.isReady = true;
  10398. };
  10399. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10400. if (!texture || texture._isDisabled) {
  10401. return;
  10402. }
  10403. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10404. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10405. try {
  10406. // Testing video texture support
  10407. if (this._videoTextureSupported === undefined) {
  10408. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10409. if (this._gl.getError() !== 0) {
  10410. this._videoTextureSupported = false;
  10411. }
  10412. else {
  10413. this._videoTextureSupported = true;
  10414. }
  10415. }
  10416. // Copy video through the current working canvas if video texture is not supported
  10417. if (!this._videoTextureSupported) {
  10418. if (!texture._workingCanvas) {
  10419. texture._workingCanvas = document.createElement("canvas");
  10420. var context = texture._workingCanvas.getContext("2d");
  10421. if (!context) {
  10422. throw new Error("Unable to get 2d context");
  10423. }
  10424. texture._workingContext = context;
  10425. texture._workingCanvas.width = texture.width;
  10426. texture._workingCanvas.height = texture.height;
  10427. }
  10428. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10429. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10430. }
  10431. else {
  10432. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10433. }
  10434. if (texture.generateMipMaps) {
  10435. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10436. }
  10437. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10438. this.resetTextureCache();
  10439. texture.isReady = true;
  10440. }
  10441. catch (ex) {
  10442. // Something unexpected
  10443. // Let's disable the texture
  10444. texture._isDisabled = true;
  10445. }
  10446. };
  10447. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10448. var fullOptions = new RenderTargetCreationOptions();
  10449. if (options !== undefined && typeof options === "object") {
  10450. fullOptions.generateMipMaps = options.generateMipMaps;
  10451. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10452. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10453. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10454. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10455. }
  10456. else {
  10457. fullOptions.generateMipMaps = options;
  10458. fullOptions.generateDepthBuffer = true;
  10459. fullOptions.generateStencilBuffer = false;
  10460. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10461. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10462. }
  10463. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10464. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10465. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10466. }
  10467. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10468. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10469. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10470. }
  10471. var gl = this._gl;
  10472. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10473. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10474. var width = size.width || size;
  10475. var height = size.height || size;
  10476. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10477. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10478. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10479. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10480. }
  10481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10484. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10485. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10486. // Create the framebuffer
  10487. var framebuffer = gl.createFramebuffer();
  10488. this.bindUnboundFramebuffer(framebuffer);
  10489. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10490. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10491. if (fullOptions.generateMipMaps) {
  10492. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10493. }
  10494. // Unbind
  10495. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10496. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10497. this.bindUnboundFramebuffer(null);
  10498. texture._framebuffer = framebuffer;
  10499. texture.baseWidth = width;
  10500. texture.baseHeight = height;
  10501. texture.width = width;
  10502. texture.height = height;
  10503. texture.isReady = true;
  10504. texture.samples = 1;
  10505. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10506. texture.samplingMode = fullOptions.samplingMode;
  10507. texture.type = fullOptions.type;
  10508. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10509. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10510. this.resetTextureCache();
  10511. this._internalTexturesCache.push(texture);
  10512. return texture;
  10513. };
  10514. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10515. var generateMipMaps = false;
  10516. var generateDepthBuffer = true;
  10517. var generateStencilBuffer = false;
  10518. var generateDepthTexture = false;
  10519. var textureCount = 1;
  10520. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10521. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10522. var types = [], samplingModes = [];
  10523. if (options !== undefined) {
  10524. generateMipMaps = options.generateMipMaps;
  10525. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10526. generateStencilBuffer = options.generateStencilBuffer;
  10527. generateDepthTexture = options.generateDepthTexture;
  10528. textureCount = options.textureCount || 1;
  10529. if (options.types) {
  10530. types = options.types;
  10531. }
  10532. if (options.samplingModes) {
  10533. samplingModes = options.samplingModes;
  10534. }
  10535. }
  10536. var gl = this._gl;
  10537. // Create the framebuffer
  10538. var framebuffer = gl.createFramebuffer();
  10539. this.bindUnboundFramebuffer(framebuffer);
  10540. var width = size.width || size;
  10541. var height = size.height || size;
  10542. var textures = [];
  10543. var attachments = [];
  10544. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10545. for (var i = 0; i < textureCount; i++) {
  10546. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10547. var type = types[i] || defaultType;
  10548. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10549. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10550. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10551. }
  10552. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10553. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10554. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10555. }
  10556. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10557. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10558. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10559. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10560. }
  10561. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10562. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10563. textures.push(texture);
  10564. attachments.push(attachment);
  10565. gl.activeTexture(gl["TEXTURE" + i]);
  10566. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10571. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10572. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10573. if (generateMipMaps) {
  10574. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10575. }
  10576. // Unbind
  10577. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10578. texture._framebuffer = framebuffer;
  10579. texture._depthStencilBuffer = depthStencilBuffer;
  10580. texture.baseWidth = width;
  10581. texture.baseHeight = height;
  10582. texture.width = width;
  10583. texture.height = height;
  10584. texture.isReady = true;
  10585. texture.samples = 1;
  10586. texture.generateMipMaps = generateMipMaps;
  10587. texture.samplingMode = samplingMode;
  10588. texture.type = type;
  10589. texture._generateDepthBuffer = generateDepthBuffer;
  10590. texture._generateStencilBuffer = generateStencilBuffer;
  10591. this._internalTexturesCache.push(texture);
  10592. }
  10593. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10594. // Depth texture
  10595. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10596. gl.activeTexture(gl.TEXTURE0);
  10597. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10598. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10599. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10600. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10601. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10602. 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);
  10603. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10604. depthTexture._framebuffer = framebuffer;
  10605. depthTexture.baseWidth = width;
  10606. depthTexture.baseHeight = height;
  10607. depthTexture.width = width;
  10608. depthTexture.height = height;
  10609. depthTexture.isReady = true;
  10610. depthTexture.samples = 1;
  10611. depthTexture.generateMipMaps = generateMipMaps;
  10612. depthTexture.samplingMode = gl.NEAREST;
  10613. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10614. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10615. textures.push(depthTexture);
  10616. this._internalTexturesCache.push(depthTexture);
  10617. }
  10618. gl.drawBuffers(attachments);
  10619. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10620. this.bindUnboundFramebuffer(null);
  10621. this.resetTextureCache();
  10622. return textures;
  10623. };
  10624. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10625. if (samples === void 0) { samples = 1; }
  10626. var depthStencilBuffer = null;
  10627. var gl = this._gl;
  10628. // Create the depth/stencil buffer
  10629. if (generateStencilBuffer) {
  10630. depthStencilBuffer = gl.createRenderbuffer();
  10631. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10632. if (samples > 1) {
  10633. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10634. }
  10635. else {
  10636. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10637. }
  10638. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10639. }
  10640. else if (generateDepthBuffer) {
  10641. depthStencilBuffer = gl.createRenderbuffer();
  10642. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10643. if (samples > 1) {
  10644. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10645. }
  10646. else {
  10647. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10648. }
  10649. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10650. }
  10651. return depthStencilBuffer;
  10652. };
  10653. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10654. if (this.webGLVersion < 2 || !texture) {
  10655. return 1;
  10656. }
  10657. if (texture.samples === samples) {
  10658. return samples;
  10659. }
  10660. var gl = this._gl;
  10661. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10662. // Dispose previous render buffers
  10663. if (texture._depthStencilBuffer) {
  10664. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10665. }
  10666. if (texture._MSAAFramebuffer) {
  10667. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10668. }
  10669. if (texture._MSAARenderBuffer) {
  10670. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10671. }
  10672. if (samples > 1) {
  10673. var framebuffer = gl.createFramebuffer();
  10674. if (!framebuffer) {
  10675. throw new Error("Unable to create multi sampled framebuffer");
  10676. }
  10677. texture._MSAAFramebuffer = framebuffer;
  10678. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10679. var colorRenderbuffer = gl.createRenderbuffer();
  10680. if (!colorRenderbuffer) {
  10681. throw new Error("Unable to create multi sampled framebuffer");
  10682. }
  10683. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10684. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10685. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10686. texture._MSAARenderBuffer = colorRenderbuffer;
  10687. }
  10688. else {
  10689. this.bindUnboundFramebuffer(texture._framebuffer);
  10690. }
  10691. texture.samples = samples;
  10692. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10693. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10694. this.bindUnboundFramebuffer(null);
  10695. return samples;
  10696. };
  10697. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10698. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10699. };
  10700. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10701. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10702. };
  10703. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10704. var gl = this._gl;
  10705. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10706. var generateMipMaps = true;
  10707. var generateDepthBuffer = true;
  10708. var generateStencilBuffer = false;
  10709. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10710. if (options !== undefined) {
  10711. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10712. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10713. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10714. if (options.samplingMode !== undefined) {
  10715. samplingMode = options.samplingMode;
  10716. }
  10717. }
  10718. texture.isCube = true;
  10719. texture.generateMipMaps = generateMipMaps;
  10720. texture.samples = 1;
  10721. texture.samplingMode = samplingMode;
  10722. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10723. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10724. for (var face = 0; face < 6; face++) {
  10725. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10726. }
  10727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10731. // Create the framebuffer
  10732. var framebuffer = gl.createFramebuffer();
  10733. this.bindUnboundFramebuffer(framebuffer);
  10734. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10735. // Mipmaps
  10736. if (texture.generateMipMaps) {
  10737. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10738. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10739. }
  10740. // Unbind
  10741. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10742. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10743. this.bindUnboundFramebuffer(null);
  10744. texture._framebuffer = framebuffer;
  10745. texture.width = size;
  10746. texture.height = size;
  10747. texture.isReady = true;
  10748. this.resetTextureCache();
  10749. this._internalTexturesCache.push(texture);
  10750. return texture;
  10751. };
  10752. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10753. var _this = this;
  10754. if (onLoad === void 0) { onLoad = null; }
  10755. if (onError === void 0) { onError = null; }
  10756. if (forcedExtension === void 0) { forcedExtension = null; }
  10757. var callback = function (loadData) {
  10758. if (!loadData) {
  10759. if (onLoad) {
  10760. onLoad(null);
  10761. }
  10762. return;
  10763. }
  10764. var texture = loadData.texture;
  10765. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10766. texture._lodGenerationScale = scale;
  10767. texture._lodGenerationOffset = offset;
  10768. if (_this._caps.textureLOD) {
  10769. // Do not add extra process if texture lod is supported.
  10770. if (onLoad) {
  10771. onLoad(texture);
  10772. }
  10773. return;
  10774. }
  10775. var mipSlices = 3;
  10776. var gl = _this._gl;
  10777. var width = loadData.width;
  10778. if (!width) {
  10779. return;
  10780. }
  10781. var textures = [];
  10782. for (var i = 0; i < mipSlices; i++) {
  10783. //compute LOD from even spacing in smoothness (matching shader calculation)
  10784. var smoothness = i / (mipSlices - 1);
  10785. var roughness = 1 - smoothness;
  10786. var minLODIndex = offset; // roughness = 0
  10787. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10788. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10789. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10790. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10791. glTextureFromLod.isCube = true;
  10792. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10797. if (loadData.isDDS) {
  10798. var info = loadData.info;
  10799. var data = loadData.data;
  10800. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10801. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10802. }
  10803. else {
  10804. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10805. }
  10806. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10807. // Wrap in a base texture for easy binding.
  10808. var lodTexture = new BABYLON.BaseTexture(scene);
  10809. lodTexture.isCube = true;
  10810. lodTexture._texture = glTextureFromLod;
  10811. glTextureFromLod.isReady = true;
  10812. textures.push(lodTexture);
  10813. }
  10814. texture._lodTextureHigh = textures[2];
  10815. texture._lodTextureMid = textures[1];
  10816. texture._lodTextureLow = textures[0];
  10817. if (onLoad) {
  10818. onLoad(texture);
  10819. }
  10820. };
  10821. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10822. };
  10823. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10824. var _this = this;
  10825. if (onLoad === void 0) { onLoad = null; }
  10826. if (onError === void 0) { onError = null; }
  10827. if (forcedExtension === void 0) { forcedExtension = null; }
  10828. var gl = this._gl;
  10829. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10830. texture.isCube = true;
  10831. texture.url = rootUrl;
  10832. texture.generateMipMaps = !noMipmap;
  10833. if (!this._doNotHandleContextLost) {
  10834. texture._extension = forcedExtension;
  10835. texture._files = files;
  10836. }
  10837. var isKTX = false;
  10838. var isDDS = false;
  10839. var lastDot = rootUrl.lastIndexOf('.');
  10840. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10841. if (this._textureFormatInUse) {
  10842. extension = this._textureFormatInUse;
  10843. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10844. isKTX = true;
  10845. }
  10846. else {
  10847. isDDS = (extension === ".dds");
  10848. }
  10849. var onerror = function (request, exception) {
  10850. if (onError) {
  10851. onError(request.status + " " + request.statusText, exception);
  10852. }
  10853. };
  10854. if (isKTX) {
  10855. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10856. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10857. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10858. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10859. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10860. ktx.uploadLevels(_this._gl, !noMipmap);
  10861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10865. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10866. _this.resetTextureCache();
  10867. texture.width = ktx.pixelWidth;
  10868. texture.height = ktx.pixelHeight;
  10869. texture.isReady = true;
  10870. }, undefined, undefined, true, onerror);
  10871. }
  10872. else if (isDDS) {
  10873. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10874. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10875. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10876. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10877. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10878. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10879. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10880. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10881. }
  10882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10887. _this.resetTextureCache();
  10888. texture.width = info.width;
  10889. texture.height = info.height;
  10890. texture.isReady = true;
  10891. texture.type = info.textureType;
  10892. if (onLoad) {
  10893. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10894. }
  10895. }, undefined, undefined, true, onerror);
  10896. }
  10897. else {
  10898. if (!files) {
  10899. throw new Error("Cannot load cubemap because files were not defined");
  10900. }
  10901. cascadeLoad(rootUrl, scene, function (imgs) {
  10902. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10903. var height = width;
  10904. _this._prepareWorkingCanvas();
  10905. if (!_this._workingCanvas || !_this._workingContext) {
  10906. return;
  10907. }
  10908. _this._workingCanvas.width = width;
  10909. _this._workingCanvas.height = height;
  10910. var faces = [
  10911. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10912. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10913. ];
  10914. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10915. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10916. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10917. for (var index = 0; index < faces.length; index++) {
  10918. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10919. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10920. }
  10921. if (!noMipmap) {
  10922. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10923. }
  10924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10926. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10928. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10929. _this.resetTextureCache();
  10930. texture.width = width;
  10931. texture.height = height;
  10932. texture.isReady = true;
  10933. if (format) {
  10934. texture.format = format;
  10935. }
  10936. texture.onLoadedObservable.notifyObservers(texture);
  10937. texture.onLoadedObservable.clear();
  10938. if (onLoad) {
  10939. onLoad();
  10940. }
  10941. }, files, onError);
  10942. }
  10943. this._internalTexturesCache.push(texture);
  10944. return texture;
  10945. };
  10946. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10947. if (compression === void 0) { compression = null; }
  10948. if (level === void 0) { level = 0; }
  10949. texture._bufferViewArray = data;
  10950. texture.format = format;
  10951. texture.type = type;
  10952. texture.invertY = invertY;
  10953. texture._compression = compression;
  10954. var gl = this._gl;
  10955. var textureType = this._getWebGLTextureType(type);
  10956. var internalFormat = this._getInternalFormat(format);
  10957. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10958. var needConversion = false;
  10959. if (internalFormat === gl.RGB) {
  10960. internalFormat = gl.RGBA;
  10961. needConversion = true;
  10962. }
  10963. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10964. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10965. if (texture.width % 4 !== 0) {
  10966. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10967. }
  10968. // Data are known to be in +X +Y +Z -X -Y -Z
  10969. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10970. var faceData = data[faceIndex];
  10971. if (compression) {
  10972. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  10973. }
  10974. else {
  10975. if (needConversion) {
  10976. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10977. }
  10978. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10979. }
  10980. }
  10981. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10982. if (isPot && texture.generateMipMaps && level === 0) {
  10983. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10984. }
  10985. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10986. this.resetTextureCache();
  10987. texture.isReady = true;
  10988. };
  10989. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10990. if (compression === void 0) { compression = null; }
  10991. var gl = this._gl;
  10992. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10993. texture.isCube = true;
  10994. texture.generateMipMaps = generateMipMaps;
  10995. texture.format = format;
  10996. texture.type = type;
  10997. if (!this._doNotHandleContextLost) {
  10998. texture._bufferViewArray = data;
  10999. }
  11000. var textureType = this._getWebGLTextureType(type);
  11001. var internalFormat = this._getInternalFormat(format);
  11002. var needConversion = false;
  11003. if (internalFormat === gl.RGB) {
  11004. internalFormat = gl.RGBA;
  11005. needConversion = true;
  11006. }
  11007. var width = size;
  11008. var height = width;
  11009. texture.width = width;
  11010. texture.height = height;
  11011. // Double check on POT to generate Mips.
  11012. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11013. if (!isPot) {
  11014. generateMipMaps = false;
  11015. }
  11016. // Upload data if needed. The texture won't be ready until then.
  11017. if (data) {
  11018. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11019. }
  11020. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11021. // Filters
  11022. if (data && generateMipMaps) {
  11023. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11024. }
  11025. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11026. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11027. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11028. }
  11029. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11030. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11031. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11032. }
  11033. else {
  11034. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11035. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11037. }
  11038. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11039. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11040. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11041. return texture;
  11042. };
  11043. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11044. var _this = this;
  11045. if (onLoad === void 0) { onLoad = null; }
  11046. if (onError === void 0) { onError = null; }
  11047. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11048. if (invertY === void 0) { invertY = false; }
  11049. var gl = this._gl;
  11050. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11051. scene._addPendingData(texture);
  11052. texture.url = url;
  11053. this._internalTexturesCache.push(texture);
  11054. var onerror = function (request, exception) {
  11055. scene._removePendingData(texture);
  11056. if (onError) {
  11057. onError(request.status + " " + request.statusText, exception);
  11058. }
  11059. };
  11060. var internalCallback = function (data) {
  11061. var width = texture.width;
  11062. var faceDataArrays = callback(data);
  11063. if (!faceDataArrays) {
  11064. return;
  11065. }
  11066. if (mipmmapGenerator) {
  11067. var textureType = _this._getWebGLTextureType(type);
  11068. var internalFormat = _this._getInternalFormat(format);
  11069. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11070. var needConversion = false;
  11071. if (internalFormat === gl.RGB) {
  11072. internalFormat = gl.RGBA;
  11073. needConversion = true;
  11074. }
  11075. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11076. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11077. var mipData = mipmmapGenerator(faceDataArrays);
  11078. for (var level = 0; level < mipData.length; level++) {
  11079. var mipSize = width >> level;
  11080. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11081. var mipFaceData = mipData[level][faceIndex];
  11082. if (needConversion) {
  11083. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11084. }
  11085. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11086. }
  11087. }
  11088. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11089. }
  11090. else {
  11091. texture.generateMipMaps = !noMipmap;
  11092. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11093. }
  11094. texture.isReady = true;
  11095. _this.resetTextureCache();
  11096. scene._removePendingData(texture);
  11097. if (onLoad) {
  11098. onLoad();
  11099. }
  11100. };
  11101. BABYLON.Tools.LoadFile(url, function (data) {
  11102. internalCallback(data);
  11103. }, undefined, scene.database, true, onerror);
  11104. return texture;
  11105. };
  11106. ;
  11107. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11108. if (compression === void 0) { compression = null; }
  11109. var internalFormat = this._getInternalFormat(format);
  11110. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11111. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11112. if (!this._doNotHandleContextLost) {
  11113. texture._bufferView = data;
  11114. texture.format = format;
  11115. texture.invertY = invertY;
  11116. texture._compression = compression;
  11117. }
  11118. if (texture.width % 4 !== 0) {
  11119. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11120. }
  11121. if (compression && data) {
  11122. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11123. }
  11124. else {
  11125. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11126. }
  11127. if (texture.generateMipMaps) {
  11128. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11129. }
  11130. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11131. this.resetTextureCache();
  11132. texture.isReady = true;
  11133. };
  11134. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11135. if (compression === void 0) { compression = null; }
  11136. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11137. texture.baseWidth = width;
  11138. texture.baseHeight = height;
  11139. texture.baseDepth = depth;
  11140. texture.width = width;
  11141. texture.height = height;
  11142. texture.depth = depth;
  11143. texture.format = format;
  11144. texture.generateMipMaps = generateMipMaps;
  11145. texture.samplingMode = samplingMode;
  11146. texture.is3D = true;
  11147. if (!this._doNotHandleContextLost) {
  11148. texture._bufferView = data;
  11149. }
  11150. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11151. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11152. // Filters
  11153. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11154. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11155. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11156. if (generateMipMaps) {
  11157. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11158. }
  11159. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11160. this._internalTexturesCache.push(texture);
  11161. return texture;
  11162. };
  11163. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11164. var gl = this._gl;
  11165. if (!gl) {
  11166. return;
  11167. }
  11168. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11170. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11171. if (!noMipmap && !isCompressed) {
  11172. gl.generateMipmap(gl.TEXTURE_2D);
  11173. }
  11174. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11175. this.resetTextureCache();
  11176. if (scene) {
  11177. scene._removePendingData(texture);
  11178. }
  11179. texture.onLoadedObservable.notifyObservers(texture);
  11180. texture.onLoadedObservable.clear();
  11181. };
  11182. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11183. var _this = this;
  11184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11185. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11186. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11187. var gl = this._gl;
  11188. if (!gl) {
  11189. return;
  11190. }
  11191. if (!texture._webGLTexture) {
  11192. this.resetTextureCache();
  11193. if (scene) {
  11194. scene._removePendingData(texture);
  11195. }
  11196. return;
  11197. }
  11198. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11199. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11200. texture.baseWidth = width;
  11201. texture.baseHeight = height;
  11202. texture.width = potWidth;
  11203. texture.height = potHeight;
  11204. texture.isReady = true;
  11205. if (processFunction(potWidth, potHeight, function () {
  11206. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11207. })) {
  11208. // Returning as texture needs extra async steps
  11209. return;
  11210. }
  11211. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11212. };
  11213. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11214. // Create new RGBA data container.
  11215. var rgbaData;
  11216. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11217. rgbaData = new Float32Array(width * height * 4);
  11218. }
  11219. else {
  11220. rgbaData = new Uint32Array(width * height * 4);
  11221. }
  11222. // Convert each pixel.
  11223. for (var x = 0; x < width; x++) {
  11224. for (var y = 0; y < height; y++) {
  11225. var index = (y * width + x) * 3;
  11226. var newIndex = (y * width + x) * 4;
  11227. // Map Old Value to new value.
  11228. rgbaData[newIndex + 0] = rgbData[index + 0];
  11229. rgbaData[newIndex + 1] = rgbData[index + 1];
  11230. rgbaData[newIndex + 2] = rgbData[index + 2];
  11231. // Add fully opaque alpha channel.
  11232. rgbaData[newIndex + 3] = 1;
  11233. }
  11234. }
  11235. return rgbaData;
  11236. };
  11237. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11238. var gl = this._gl;
  11239. if (texture._framebuffer) {
  11240. gl.deleteFramebuffer(texture._framebuffer);
  11241. texture._framebuffer = null;
  11242. }
  11243. if (texture._depthStencilBuffer) {
  11244. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11245. texture._depthStencilBuffer = null;
  11246. }
  11247. if (texture._MSAAFramebuffer) {
  11248. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11249. texture._MSAAFramebuffer = null;
  11250. }
  11251. if (texture._MSAARenderBuffer) {
  11252. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11253. texture._MSAARenderBuffer = null;
  11254. }
  11255. };
  11256. Engine.prototype._releaseTexture = function (texture) {
  11257. var gl = this._gl;
  11258. this._releaseFramebufferObjects(texture);
  11259. gl.deleteTexture(texture._webGLTexture);
  11260. // Unbind channels
  11261. this.unbindAllTextures();
  11262. var index = this._internalTexturesCache.indexOf(texture);
  11263. if (index !== -1) {
  11264. this._internalTexturesCache.splice(index, 1);
  11265. }
  11266. // Integrated fixed lod samplers.
  11267. if (texture._lodTextureHigh) {
  11268. texture._lodTextureHigh.dispose();
  11269. }
  11270. if (texture._lodTextureMid) {
  11271. texture._lodTextureMid.dispose();
  11272. }
  11273. if (texture._lodTextureLow) {
  11274. texture._lodTextureLow.dispose();
  11275. }
  11276. };
  11277. Engine.prototype.setProgram = function (program) {
  11278. if (this._currentProgram !== program) {
  11279. this._gl.useProgram(program);
  11280. this._currentProgram = program;
  11281. }
  11282. };
  11283. Engine.prototype.bindSamplers = function (effect) {
  11284. this.setProgram(effect.getProgram());
  11285. var samplers = effect.getSamplers();
  11286. for (var index = 0; index < samplers.length; index++) {
  11287. var uniform = effect.getUniform(samplers[index]);
  11288. this._gl.uniform1i(uniform, index);
  11289. }
  11290. this._currentEffect = null;
  11291. };
  11292. Engine.prototype.activateTexture = function (texture) {
  11293. if (this._activeTexture !== texture) {
  11294. this._gl.activeTexture(texture);
  11295. this._activeTexture = texture;
  11296. }
  11297. };
  11298. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11299. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11300. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11301. this._activeTexturesCache[this._activeTexture] = texture;
  11302. }
  11303. };
  11304. Engine.prototype._bindTexture = function (channel, texture) {
  11305. if (channel < 0) {
  11306. return;
  11307. }
  11308. this.activateTexture(this._gl.TEXTURE0 + channel);
  11309. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11310. };
  11311. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11312. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11313. };
  11314. Engine.prototype.unbindAllTextures = function () {
  11315. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11316. this.activateTexture(this._gl["TEXTURE" + channel]);
  11317. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11318. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11319. if (this.webGLVersion > 1) {
  11320. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11321. }
  11322. }
  11323. };
  11324. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11325. if (channel < 0) {
  11326. return;
  11327. }
  11328. this._gl.uniform1i(uniform, channel);
  11329. this._setTexture(channel, texture);
  11330. };
  11331. Engine.prototype._setTexture = function (channel, texture) {
  11332. // Not ready?
  11333. if (!texture) {
  11334. if (this._activeTexturesCache[channel] != null) {
  11335. this.activateTexture(this._gl["TEXTURE" + channel]);
  11336. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11337. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11338. if (this.webGLVersion > 1) {
  11339. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11340. }
  11341. }
  11342. return;
  11343. }
  11344. // Video
  11345. var alreadyActivated = false;
  11346. if (texture.video) {
  11347. this.activateTexture(this._gl["TEXTURE" + channel]);
  11348. alreadyActivated = true;
  11349. texture.update();
  11350. }
  11351. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11352. texture.delayLoad();
  11353. return;
  11354. }
  11355. var internalTexture;
  11356. if (texture.isReady()) {
  11357. internalTexture = texture.getInternalTexture();
  11358. }
  11359. else if (texture.isCube) {
  11360. internalTexture = this.emptyCubeTexture;
  11361. }
  11362. else if (texture.is3D) {
  11363. internalTexture = this.emptyTexture3D;
  11364. }
  11365. else {
  11366. internalTexture = this.emptyTexture;
  11367. }
  11368. if (this._activeTexturesCache[channel] === internalTexture) {
  11369. return;
  11370. }
  11371. if (!alreadyActivated) {
  11372. this.activateTexture(this._gl["TEXTURE" + channel]);
  11373. }
  11374. if (internalTexture && internalTexture.is3D) {
  11375. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11376. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11377. internalTexture._cachedWrapU = texture.wrapU;
  11378. switch (texture.wrapU) {
  11379. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11380. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11381. break;
  11382. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11383. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11384. break;
  11385. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11386. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11387. break;
  11388. }
  11389. }
  11390. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11391. internalTexture._cachedWrapV = texture.wrapV;
  11392. switch (texture.wrapV) {
  11393. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11394. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11395. break;
  11396. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11397. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11398. break;
  11399. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11400. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11401. break;
  11402. }
  11403. }
  11404. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11405. internalTexture._cachedWrapR = texture.wrapR;
  11406. switch (texture.wrapV) {
  11407. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11408. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11409. break;
  11410. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11411. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11412. break;
  11413. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11414. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11415. break;
  11416. }
  11417. }
  11418. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11419. }
  11420. else if (internalTexture && internalTexture.isCube) {
  11421. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11422. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11423. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11424. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11425. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11426. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11427. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11428. }
  11429. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11430. }
  11431. else {
  11432. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11433. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11434. internalTexture._cachedWrapU = texture.wrapU;
  11435. switch (texture.wrapU) {
  11436. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11437. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11438. break;
  11439. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11440. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11441. break;
  11442. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11443. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11444. break;
  11445. }
  11446. }
  11447. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11448. internalTexture._cachedWrapV = texture.wrapV;
  11449. switch (texture.wrapV) {
  11450. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11451. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11452. break;
  11453. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11454. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11455. break;
  11456. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11457. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11458. break;
  11459. }
  11460. }
  11461. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11462. }
  11463. };
  11464. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11465. if (channel < 0 || !uniform) {
  11466. return;
  11467. }
  11468. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11469. this._textureUnits = new Int32Array(textures.length);
  11470. }
  11471. for (var i = 0; i < textures.length; i++) {
  11472. this._textureUnits[i] = channel + i;
  11473. }
  11474. this._gl.uniform1iv(uniform, this._textureUnits);
  11475. for (var index = 0; index < textures.length; index++) {
  11476. this._setTexture(channel + index, textures[index]);
  11477. }
  11478. };
  11479. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11480. var internalTexture = texture.getInternalTexture();
  11481. if (!internalTexture) {
  11482. return;
  11483. }
  11484. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11485. var value = texture.anisotropicFilteringLevel;
  11486. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11487. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11488. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11489. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11490. }
  11491. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11492. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11493. internalTexture._cachedAnisotropicFilteringLevel = value;
  11494. }
  11495. };
  11496. Engine.prototype.readPixels = function (x, y, width, height) {
  11497. var data = new Uint8Array(height * width * 4);
  11498. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11499. return data;
  11500. };
  11501. /**
  11502. * Add an externaly attached data from its key.
  11503. * This method call will fail and return false, if such key already exists.
  11504. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11505. * @param key the unique key that identifies the data
  11506. * @param data the data object to associate to the key for this Engine instance
  11507. * @return true if no such key were already present and the data was added successfully, false otherwise
  11508. */
  11509. Engine.prototype.addExternalData = function (key, data) {
  11510. if (!this._externalData) {
  11511. this._externalData = new BABYLON.StringDictionary();
  11512. }
  11513. return this._externalData.add(key, data);
  11514. };
  11515. /**
  11516. * Get an externaly attached data from its key
  11517. * @param key the unique key that identifies the data
  11518. * @return the associated data, if present (can be null), or undefined if not present
  11519. */
  11520. Engine.prototype.getExternalData = function (key) {
  11521. if (!this._externalData) {
  11522. this._externalData = new BABYLON.StringDictionary();
  11523. }
  11524. return this._externalData.get(key);
  11525. };
  11526. /**
  11527. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11528. * @param key the unique key that identifies the data
  11529. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11530. * @return the associated data, can be null if the factory returned null.
  11531. */
  11532. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11533. if (!this._externalData) {
  11534. this._externalData = new BABYLON.StringDictionary();
  11535. }
  11536. return this._externalData.getOrAddWithFactory(key, factory);
  11537. };
  11538. /**
  11539. * Remove an externaly attached data from the Engine instance
  11540. * @param key the unique key that identifies the data
  11541. * @return true if the data was successfully removed, false if it doesn't exist
  11542. */
  11543. Engine.prototype.removeExternalData = function (key) {
  11544. if (!this._externalData) {
  11545. this._externalData = new BABYLON.StringDictionary();
  11546. }
  11547. return this._externalData.remove(key);
  11548. };
  11549. Engine.prototype.unbindAllAttributes = function () {
  11550. if (this._mustWipeVertexAttributes) {
  11551. this._mustWipeVertexAttributes = false;
  11552. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11553. this._gl.disableVertexAttribArray(i);
  11554. this._vertexAttribArraysEnabled[i] = false;
  11555. this._currentBufferPointers[i].active = false;
  11556. }
  11557. return;
  11558. }
  11559. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11560. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11561. continue;
  11562. }
  11563. this._gl.disableVertexAttribArray(i);
  11564. this._vertexAttribArraysEnabled[i] = false;
  11565. this._currentBufferPointers[i].active = false;
  11566. }
  11567. };
  11568. Engine.prototype.releaseEffects = function () {
  11569. for (var name in this._compiledEffects) {
  11570. this._deleteProgram(this._compiledEffects[name]._program);
  11571. }
  11572. this._compiledEffects = {};
  11573. };
  11574. // Dispose
  11575. Engine.prototype.dispose = function () {
  11576. this.hideLoadingUI();
  11577. this.stopRenderLoop();
  11578. // Release postProcesses
  11579. while (this.postProcesses.length) {
  11580. this.postProcesses[0].dispose();
  11581. }
  11582. // Empty texture
  11583. if (this._emptyTexture) {
  11584. this._releaseTexture(this._emptyTexture);
  11585. this._emptyTexture = null;
  11586. }
  11587. if (this._emptyCubeTexture) {
  11588. this._releaseTexture(this._emptyCubeTexture);
  11589. this._emptyCubeTexture = null;
  11590. }
  11591. // Rescale PP
  11592. if (this._rescalePostProcess) {
  11593. this._rescalePostProcess.dispose();
  11594. }
  11595. // Release scenes
  11596. while (this.scenes.length) {
  11597. this.scenes[0].dispose();
  11598. }
  11599. // Release audio engine
  11600. if (Engine.audioEngine) {
  11601. Engine.audioEngine.dispose();
  11602. }
  11603. // Release effects
  11604. this.releaseEffects();
  11605. // Unbind
  11606. this.unbindAllAttributes();
  11607. if (this._dummyFramebuffer) {
  11608. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11609. }
  11610. //WebVR
  11611. this.disableVR();
  11612. // Events
  11613. window.removeEventListener("blur", this._onBlur);
  11614. window.removeEventListener("focus", this._onFocus);
  11615. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11616. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11617. if (this._renderingCanvas) {
  11618. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11619. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11620. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11621. if (!this._doNotHandleContextLost) {
  11622. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11623. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11624. }
  11625. }
  11626. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11627. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11628. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11629. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11630. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11631. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11632. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11633. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11634. if (this._onVrDisplayConnect) {
  11635. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11636. if (this._onVrDisplayDisconnect) {
  11637. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11638. }
  11639. if (this._onVrDisplayPresentChange) {
  11640. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11641. }
  11642. this._onVrDisplayConnect = null;
  11643. this._onVrDisplayDisconnect = null;
  11644. }
  11645. // Remove from Instances
  11646. var index = Engine.Instances.indexOf(this);
  11647. if (index >= 0) {
  11648. Engine.Instances.splice(index, 1);
  11649. }
  11650. this._workingCanvas = null;
  11651. this._workingContext = null;
  11652. this._currentBufferPointers = [];
  11653. this._renderingCanvas = null;
  11654. this._currentProgram = null;
  11655. this.onResizeObservable.clear();
  11656. this.onCanvasBlurObservable.clear();
  11657. this.onCanvasFocusObservable.clear();
  11658. this.onCanvasPointerOutObservable.clear();
  11659. BABYLON.Effect.ResetCache();
  11660. };
  11661. // Loading screen
  11662. Engine.prototype.displayLoadingUI = function () {
  11663. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11664. return;
  11665. }
  11666. var loadingScreen = this.loadingScreen;
  11667. if (loadingScreen) {
  11668. loadingScreen.displayLoadingUI();
  11669. }
  11670. };
  11671. Engine.prototype.hideLoadingUI = function () {
  11672. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11673. return;
  11674. }
  11675. var loadingScreen = this.loadingScreen;
  11676. if (loadingScreen) {
  11677. loadingScreen.hideLoadingUI();
  11678. }
  11679. };
  11680. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11681. get: function () {
  11682. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11683. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11684. return this._loadingScreen;
  11685. },
  11686. set: function (loadingScreen) {
  11687. this._loadingScreen = loadingScreen;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11693. set: function (text) {
  11694. this.loadingScreen.loadingUIText = text;
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11700. set: function (color) {
  11701. this.loadingScreen.loadingUIBackgroundColor = color;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Engine.prototype.attachContextLostEvent = function (callback) {
  11707. if (this._renderingCanvas) {
  11708. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11709. }
  11710. };
  11711. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11712. if (this._renderingCanvas) {
  11713. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11714. }
  11715. };
  11716. Engine.prototype.getVertexShaderSource = function (program) {
  11717. var shaders = this._gl.getAttachedShaders(program);
  11718. if (!shaders) {
  11719. return null;
  11720. }
  11721. return this._gl.getShaderSource(shaders[0]);
  11722. };
  11723. Engine.prototype.getFragmentShaderSource = function (program) {
  11724. var shaders = this._gl.getAttachedShaders(program);
  11725. if (!shaders) {
  11726. return null;
  11727. }
  11728. return this._gl.getShaderSource(shaders[1]);
  11729. };
  11730. Engine.prototype.getError = function () {
  11731. return this._gl.getError();
  11732. };
  11733. // FPS
  11734. Engine.prototype.getFps = function () {
  11735. return this._fps;
  11736. };
  11737. Engine.prototype.getDeltaTime = function () {
  11738. return this._deltaTime;
  11739. };
  11740. Engine.prototype._measureFps = function () {
  11741. this._performanceMonitor.sampleFrame();
  11742. this._fps = this._performanceMonitor.averageFPS;
  11743. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11744. };
  11745. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11746. if (faceIndex === void 0) { faceIndex = -1; }
  11747. var gl = this._gl;
  11748. if (!this._dummyFramebuffer) {
  11749. var dummy = gl.createFramebuffer();
  11750. if (!dummy) {
  11751. throw new Error("Unable to create dummy framebuffer");
  11752. }
  11753. this._dummyFramebuffer = dummy;
  11754. }
  11755. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11756. if (faceIndex > -1) {
  11757. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11758. }
  11759. else {
  11760. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11761. }
  11762. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11763. var buffer;
  11764. switch (readType) {
  11765. case gl.UNSIGNED_BYTE:
  11766. buffer = new Uint8Array(4 * width * height);
  11767. readType = gl.UNSIGNED_BYTE;
  11768. break;
  11769. default:
  11770. buffer = new Float32Array(4 * width * height);
  11771. readType = gl.FLOAT;
  11772. break;
  11773. }
  11774. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11775. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11776. return buffer;
  11777. };
  11778. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11779. if (this._webGLVersion > 1) {
  11780. return this._caps.colorBufferFloat;
  11781. }
  11782. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11783. };
  11784. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11785. if (this._webGLVersion > 1) {
  11786. return this._caps.colorBufferFloat;
  11787. }
  11788. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11789. };
  11790. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11791. Engine.prototype._canRenderToFramebuffer = function (type) {
  11792. var gl = this._gl;
  11793. //clear existing errors
  11794. while (gl.getError() !== gl.NO_ERROR) { }
  11795. var successful = true;
  11796. var texture = gl.createTexture();
  11797. gl.bindTexture(gl.TEXTURE_2D, texture);
  11798. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11801. var fb = gl.createFramebuffer();
  11802. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11803. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11804. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11805. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11806. successful = successful && (gl.getError() === gl.NO_ERROR);
  11807. //try render by clearing frame buffer's color buffer
  11808. if (successful) {
  11809. gl.clear(gl.COLOR_BUFFER_BIT);
  11810. successful = successful && (gl.getError() === gl.NO_ERROR);
  11811. }
  11812. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11813. if (successful) {
  11814. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11815. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11816. var readFormat = gl.RGBA;
  11817. var readType = gl.UNSIGNED_BYTE;
  11818. var buffer = new Uint8Array(4);
  11819. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11820. successful = successful && (gl.getError() === gl.NO_ERROR);
  11821. }
  11822. //clean up
  11823. gl.deleteTexture(texture);
  11824. gl.deleteFramebuffer(fb);
  11825. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11826. //clear accumulated errors
  11827. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11828. return successful;
  11829. };
  11830. Engine.prototype._getWebGLTextureType = function (type) {
  11831. if (type === Engine.TEXTURETYPE_FLOAT) {
  11832. return this._gl.FLOAT;
  11833. }
  11834. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11835. // Add Half Float Constant.
  11836. return this._gl.HALF_FLOAT_OES;
  11837. }
  11838. return this._gl.UNSIGNED_BYTE;
  11839. };
  11840. ;
  11841. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11842. if (this._webGLVersion === 1) {
  11843. return this._gl.RGBA;
  11844. }
  11845. if (type === Engine.TEXTURETYPE_FLOAT) {
  11846. return this._gl.RGBA32F;
  11847. }
  11848. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11849. return this._gl.RGBA16F;
  11850. }
  11851. return this._gl.RGBA;
  11852. };
  11853. ;
  11854. Engine.prototype.createQuery = function () {
  11855. return this._gl.createQuery();
  11856. };
  11857. Engine.prototype.deleteQuery = function (query) {
  11858. this._gl.deleteQuery(query);
  11859. return this;
  11860. };
  11861. Engine.prototype.isQueryResultAvailable = function (query) {
  11862. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11863. };
  11864. Engine.prototype.getQueryResult = function (query) {
  11865. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11866. };
  11867. Engine.prototype.beginQuery = function (algorithmType, query) {
  11868. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11869. this._gl.beginQuery(glAlgorithm, query);
  11870. };
  11871. Engine.prototype.endQuery = function (algorithmType) {
  11872. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11873. this._gl.endQuery(glAlgorithm);
  11874. return this;
  11875. };
  11876. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11877. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11878. };
  11879. // Statics
  11880. Engine.isSupported = function () {
  11881. try {
  11882. var tempcanvas = document.createElement("canvas");
  11883. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11884. return gl != null && !!window.WebGLRenderingContext;
  11885. }
  11886. catch (e) {
  11887. return false;
  11888. }
  11889. };
  11890. Engine.Instances = new Array();
  11891. // Const statics
  11892. Engine._ALPHA_DISABLE = 0;
  11893. Engine._ALPHA_ADD = 1;
  11894. Engine._ALPHA_COMBINE = 2;
  11895. Engine._ALPHA_SUBTRACT = 3;
  11896. Engine._ALPHA_MULTIPLY = 4;
  11897. Engine._ALPHA_MAXIMIZED = 5;
  11898. Engine._ALPHA_ONEONE = 6;
  11899. Engine._ALPHA_PREMULTIPLIED = 7;
  11900. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11901. Engine._ALPHA_INTERPOLATE = 9;
  11902. Engine._ALPHA_SCREENMODE = 10;
  11903. Engine._DELAYLOADSTATE_NONE = 0;
  11904. Engine._DELAYLOADSTATE_LOADED = 1;
  11905. Engine._DELAYLOADSTATE_LOADING = 2;
  11906. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11907. Engine._TEXTUREFORMAT_ALPHA = 0;
  11908. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11909. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11910. Engine._TEXTUREFORMAT_RGB = 4;
  11911. Engine._TEXTUREFORMAT_RGBA = 5;
  11912. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11913. Engine._TEXTURETYPE_FLOAT = 1;
  11914. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11915. // Depht or Stencil test Constants.
  11916. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11917. 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.
  11918. 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.
  11919. 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.
  11920. 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.
  11921. 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.
  11922. 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.
  11923. 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.
  11924. // Stencil Actions Constants.
  11925. Engine._KEEP = 0x1E00;
  11926. Engine._REPLACE = 0x1E01;
  11927. Engine._INCR = 0x1E02;
  11928. Engine._DECR = 0x1E03;
  11929. Engine._INVERT = 0x150A;
  11930. Engine._INCR_WRAP = 0x8507;
  11931. Engine._DECR_WRAP = 0x8508;
  11932. // Texture rescaling mode
  11933. Engine._SCALEMODE_FLOOR = 1;
  11934. Engine._SCALEMODE_NEAREST = 2;
  11935. Engine._SCALEMODE_CEILING = 3;
  11936. // Updatable statics so stick with vars here
  11937. Engine.CollisionsEpsilon = 0.001;
  11938. Engine.CodeRepository = "src/";
  11939. Engine.ShadersRepository = "src/Shaders/";
  11940. return Engine;
  11941. }());
  11942. BABYLON.Engine = Engine;
  11943. })(BABYLON || (BABYLON = {}));
  11944. //# sourceMappingURL=babylon.engine.js.map
  11945. /// <reference path="Tools\babylon.decorators.ts" />
  11946. var BABYLON;
  11947. (function (BABYLON) {
  11948. /**
  11949. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11950. */
  11951. var Node = /** @class */ (function () {
  11952. /**
  11953. * @constructor
  11954. * @param {string} name - the name and id to be given to this node
  11955. * @param {BABYLON.Scene} the scene this node will be added to
  11956. */
  11957. function Node(name, scene) {
  11958. if (scene === void 0) { scene = null; }
  11959. this.state = "";
  11960. this.metadata = null;
  11961. this.doNotSerialize = false;
  11962. this.animations = new Array();
  11963. this._ranges = {};
  11964. this._isEnabled = true;
  11965. this._isReady = true;
  11966. this._currentRenderId = -1;
  11967. this._parentRenderId = -1;
  11968. /**
  11969. * An event triggered when the mesh is disposed.
  11970. * @type {BABYLON.Observable}
  11971. */
  11972. this.onDisposeObservable = new BABYLON.Observable();
  11973. // Behaviors
  11974. this._behaviors = new Array();
  11975. this.name = name;
  11976. this.id = name;
  11977. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  11978. this.uniqueId = this._scene.getUniqueId();
  11979. this._initCache();
  11980. }
  11981. Object.defineProperty(Node.prototype, "parent", {
  11982. get: function () {
  11983. return this._parentNode;
  11984. },
  11985. set: function (parent) {
  11986. if (this._parentNode === parent) {
  11987. return;
  11988. }
  11989. if (this._parentNode) {
  11990. var index = this._parentNode._children.indexOf(this);
  11991. if (index !== -1) {
  11992. this._parentNode._children.splice(index, 1);
  11993. }
  11994. }
  11995. this._parentNode = parent;
  11996. if (this._parentNode) {
  11997. if (!this._parentNode._children) {
  11998. this._parentNode._children = new Array();
  11999. }
  12000. this._parentNode._children.push(this);
  12001. }
  12002. },
  12003. enumerable: true,
  12004. configurable: true
  12005. });
  12006. Node.prototype.getClassName = function () {
  12007. return "Node";
  12008. };
  12009. Object.defineProperty(Node.prototype, "onDispose", {
  12010. set: function (callback) {
  12011. if (this._onDisposeObserver) {
  12012. this.onDisposeObservable.remove(this._onDisposeObserver);
  12013. }
  12014. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Node.prototype.getScene = function () {
  12020. return this._scene;
  12021. };
  12022. Node.prototype.getEngine = function () {
  12023. return this._scene.getEngine();
  12024. };
  12025. Node.prototype.addBehavior = function (behavior) {
  12026. var index = this._behaviors.indexOf(behavior);
  12027. if (index !== -1) {
  12028. return this;
  12029. }
  12030. behavior.attach(this);
  12031. this._behaviors.push(behavior);
  12032. return this;
  12033. };
  12034. Node.prototype.removeBehavior = function (behavior) {
  12035. var index = this._behaviors.indexOf(behavior);
  12036. if (index === -1) {
  12037. return this;
  12038. }
  12039. this._behaviors[index].detach();
  12040. this._behaviors.splice(index, 1);
  12041. return this;
  12042. };
  12043. Object.defineProperty(Node.prototype, "behaviors", {
  12044. get: function () {
  12045. return this._behaviors;
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Node.prototype.getBehaviorByName = function (name) {
  12051. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12052. var behavior = _a[_i];
  12053. if (behavior.name === name) {
  12054. return behavior;
  12055. }
  12056. }
  12057. return null;
  12058. };
  12059. // override it in derived class
  12060. Node.prototype.getWorldMatrix = function () {
  12061. return BABYLON.Matrix.Identity();
  12062. };
  12063. // override it in derived class if you add new variables to the cache
  12064. // and call the parent class method
  12065. Node.prototype._initCache = function () {
  12066. this._cache = {};
  12067. this._cache.parent = undefined;
  12068. };
  12069. Node.prototype.updateCache = function (force) {
  12070. if (!force && this.isSynchronized())
  12071. return;
  12072. this._cache.parent = this.parent;
  12073. this._updateCache();
  12074. };
  12075. // override it in derived class if you add new variables to the cache
  12076. // and call the parent class method if !ignoreParentClass
  12077. Node.prototype._updateCache = function (ignoreParentClass) {
  12078. };
  12079. // override it in derived class if you add new variables to the cache
  12080. Node.prototype._isSynchronized = function () {
  12081. return true;
  12082. };
  12083. Node.prototype._markSyncedWithParent = function () {
  12084. if (this.parent) {
  12085. this._parentRenderId = this.parent._currentRenderId;
  12086. }
  12087. };
  12088. Node.prototype.isSynchronizedWithParent = function () {
  12089. if (!this.parent) {
  12090. return true;
  12091. }
  12092. if (this._parentRenderId !== this.parent._currentRenderId) {
  12093. return false;
  12094. }
  12095. return this.parent.isSynchronized();
  12096. };
  12097. Node.prototype.isSynchronized = function (updateCache) {
  12098. var check = this.hasNewParent();
  12099. check = check || !this.isSynchronizedWithParent();
  12100. check = check || !this._isSynchronized();
  12101. if (updateCache)
  12102. this.updateCache(true);
  12103. return !check;
  12104. };
  12105. Node.prototype.hasNewParent = function (update) {
  12106. if (this._cache.parent === this.parent)
  12107. return false;
  12108. if (update)
  12109. this._cache.parent = this.parent;
  12110. return true;
  12111. };
  12112. /**
  12113. * Is this node ready to be used/rendered
  12114. * @return {boolean} is it ready
  12115. */
  12116. Node.prototype.isReady = function () {
  12117. return this._isReady;
  12118. };
  12119. /**
  12120. * Is this node enabled.
  12121. * If the node has a parent and is enabled, the parent will be inspected as well.
  12122. * @return {boolean} whether this node (and its parent) is enabled.
  12123. * @see setEnabled
  12124. */
  12125. Node.prototype.isEnabled = function () {
  12126. if (!this._isEnabled) {
  12127. return false;
  12128. }
  12129. if (this.parent) {
  12130. return this.parent.isEnabled();
  12131. }
  12132. return true;
  12133. };
  12134. /**
  12135. * Set the enabled state of this node.
  12136. * @param {boolean} value - the new enabled state
  12137. * @see isEnabled
  12138. */
  12139. Node.prototype.setEnabled = function (value) {
  12140. this._isEnabled = value;
  12141. };
  12142. /**
  12143. * Is this node a descendant of the given node.
  12144. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12145. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12146. * @see parent
  12147. */
  12148. Node.prototype.isDescendantOf = function (ancestor) {
  12149. if (this.parent) {
  12150. if (this.parent === ancestor) {
  12151. return true;
  12152. }
  12153. return this.parent.isDescendantOf(ancestor);
  12154. }
  12155. return false;
  12156. };
  12157. /**
  12158. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12159. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12160. * @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.
  12161. * @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.
  12162. */
  12163. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12164. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12165. if (!this._children) {
  12166. return;
  12167. }
  12168. for (var index = 0; index < this._children.length; index++) {
  12169. var item = this._children[index];
  12170. if (!predicate || predicate(item)) {
  12171. results.push(item);
  12172. }
  12173. if (!directDescendantsOnly) {
  12174. item._getDescendants(results, false, predicate);
  12175. }
  12176. }
  12177. };
  12178. /**
  12179. * Will return all nodes that have this node as ascendant.
  12180. * @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.
  12181. * @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.
  12182. * @return {BABYLON.Node[]} all children nodes of all types.
  12183. */
  12184. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12185. var results = new Array();
  12186. this._getDescendants(results, directDescendantsOnly, predicate);
  12187. return results;
  12188. };
  12189. /**
  12190. * Get all child-meshes of this node.
  12191. */
  12192. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12193. var results = [];
  12194. this._getDescendants(results, directDecendantsOnly, function (node) {
  12195. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12196. });
  12197. return results;
  12198. };
  12199. /**
  12200. * Get all direct children of this node.
  12201. */
  12202. Node.prototype.getChildren = function (predicate) {
  12203. return this.getDescendants(true, predicate);
  12204. };
  12205. Node.prototype._setReady = function (state) {
  12206. if (state === this._isReady) {
  12207. return;
  12208. }
  12209. if (!state) {
  12210. this._isReady = false;
  12211. return;
  12212. }
  12213. this._isReady = true;
  12214. if (this.onReady) {
  12215. this.onReady(this);
  12216. }
  12217. };
  12218. Node.prototype.getAnimationByName = function (name) {
  12219. for (var i = 0; i < this.animations.length; i++) {
  12220. var animation = this.animations[i];
  12221. if (animation.name === name) {
  12222. return animation;
  12223. }
  12224. }
  12225. return null;
  12226. };
  12227. Node.prototype.createAnimationRange = function (name, from, to) {
  12228. // check name not already in use
  12229. if (!this._ranges[name]) {
  12230. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12231. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12232. if (this.animations[i]) {
  12233. this.animations[i].createRange(name, from, to);
  12234. }
  12235. }
  12236. }
  12237. };
  12238. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12239. if (deleteFrames === void 0) { deleteFrames = true; }
  12240. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12241. if (this.animations[i]) {
  12242. this.animations[i].deleteRange(name, deleteFrames);
  12243. }
  12244. }
  12245. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12246. };
  12247. Node.prototype.getAnimationRange = function (name) {
  12248. return this._ranges[name];
  12249. };
  12250. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12251. var range = this.getAnimationRange(name);
  12252. if (!range) {
  12253. return;
  12254. }
  12255. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12256. };
  12257. Node.prototype.serializeAnimationRanges = function () {
  12258. var serializationRanges = [];
  12259. for (var name in this._ranges) {
  12260. var localRange = this._ranges[name];
  12261. if (!localRange) {
  12262. continue;
  12263. }
  12264. var range = {};
  12265. range.name = name;
  12266. range.from = localRange.from;
  12267. range.to = localRange.to;
  12268. serializationRanges.push(range);
  12269. }
  12270. return serializationRanges;
  12271. };
  12272. Node.prototype.dispose = function () {
  12273. this.parent = null;
  12274. // Callback
  12275. this.onDisposeObservable.notifyObservers(this);
  12276. this.onDisposeObservable.clear();
  12277. // Behaviors
  12278. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12279. var behavior = _a[_i];
  12280. behavior.detach();
  12281. }
  12282. this._behaviors = [];
  12283. };
  12284. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12285. if (parsedNode.ranges) {
  12286. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12287. var data = parsedNode.ranges[index];
  12288. node.createAnimationRange(data.name, data.from, data.to);
  12289. }
  12290. }
  12291. };
  12292. __decorate([
  12293. BABYLON.serialize()
  12294. ], Node.prototype, "name", void 0);
  12295. __decorate([
  12296. BABYLON.serialize()
  12297. ], Node.prototype, "id", void 0);
  12298. __decorate([
  12299. BABYLON.serialize()
  12300. ], Node.prototype, "uniqueId", void 0);
  12301. __decorate([
  12302. BABYLON.serialize()
  12303. ], Node.prototype, "state", void 0);
  12304. __decorate([
  12305. BABYLON.serialize()
  12306. ], Node.prototype, "metadata", void 0);
  12307. return Node;
  12308. }());
  12309. BABYLON.Node = Node;
  12310. })(BABYLON || (BABYLON = {}));
  12311. //# sourceMappingURL=babylon.node.js.map
  12312. var BABYLON;
  12313. (function (BABYLON) {
  12314. var BoundingSphere = /** @class */ (function () {
  12315. function BoundingSphere(minimum, maximum) {
  12316. this.minimum = minimum;
  12317. this.maximum = maximum;
  12318. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12319. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12320. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12321. this.radius = distance * 0.5;
  12322. this.centerWorld = BABYLON.Vector3.Zero();
  12323. this._update(BABYLON.Matrix.Identity());
  12324. }
  12325. // Methods
  12326. BoundingSphere.prototype._update = function (world) {
  12327. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12328. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12329. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12330. };
  12331. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12332. for (var i = 0; i < 6; i++) {
  12333. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12334. return false;
  12335. }
  12336. return true;
  12337. };
  12338. BoundingSphere.prototype.intersectsPoint = function (point) {
  12339. var x = this.centerWorld.x - point.x;
  12340. var y = this.centerWorld.y - point.y;
  12341. var z = this.centerWorld.z - point.z;
  12342. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12343. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12344. return false;
  12345. return true;
  12346. };
  12347. // Statics
  12348. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12349. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12350. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12351. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12352. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12353. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12354. return false;
  12355. return true;
  12356. };
  12357. return BoundingSphere;
  12358. }());
  12359. BABYLON.BoundingSphere = BoundingSphere;
  12360. })(BABYLON || (BABYLON = {}));
  12361. //# sourceMappingURL=babylon.boundingSphere.js.map
  12362. var BABYLON;
  12363. (function (BABYLON) {
  12364. var BoundingBox = /** @class */ (function () {
  12365. function BoundingBox(minimum, maximum) {
  12366. this.minimum = minimum;
  12367. this.maximum = maximum;
  12368. this.vectors = new Array();
  12369. this.vectorsWorld = new Array();
  12370. // Bounding vectors
  12371. this.vectors.push(this.minimum.clone());
  12372. this.vectors.push(this.maximum.clone());
  12373. this.vectors.push(this.minimum.clone());
  12374. this.vectors[2].x = this.maximum.x;
  12375. this.vectors.push(this.minimum.clone());
  12376. this.vectors[3].y = this.maximum.y;
  12377. this.vectors.push(this.minimum.clone());
  12378. this.vectors[4].z = this.maximum.z;
  12379. this.vectors.push(this.maximum.clone());
  12380. this.vectors[5].z = this.minimum.z;
  12381. this.vectors.push(this.maximum.clone());
  12382. this.vectors[6].x = this.minimum.x;
  12383. this.vectors.push(this.maximum.clone());
  12384. this.vectors[7].y = this.minimum.y;
  12385. // OBB
  12386. this.center = this.maximum.add(this.minimum).scale(0.5);
  12387. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12388. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12389. // World
  12390. for (var index = 0; index < this.vectors.length; index++) {
  12391. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12392. }
  12393. this.minimumWorld = BABYLON.Vector3.Zero();
  12394. this.maximumWorld = BABYLON.Vector3.Zero();
  12395. this.centerWorld = BABYLON.Vector3.Zero();
  12396. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12397. this._update(BABYLON.Matrix.Identity());
  12398. }
  12399. // Methods
  12400. BoundingBox.prototype.getWorldMatrix = function () {
  12401. return this._worldMatrix;
  12402. };
  12403. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12404. this._worldMatrix.copyFrom(matrix);
  12405. return this;
  12406. };
  12407. BoundingBox.prototype._update = function (world) {
  12408. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12409. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12410. for (var index = 0; index < this.vectors.length; index++) {
  12411. var v = this.vectorsWorld[index];
  12412. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12413. if (v.x < this.minimumWorld.x)
  12414. this.minimumWorld.x = v.x;
  12415. if (v.y < this.minimumWorld.y)
  12416. this.minimumWorld.y = v.y;
  12417. if (v.z < this.minimumWorld.z)
  12418. this.minimumWorld.z = v.z;
  12419. if (v.x > this.maximumWorld.x)
  12420. this.maximumWorld.x = v.x;
  12421. if (v.y > this.maximumWorld.y)
  12422. this.maximumWorld.y = v.y;
  12423. if (v.z > this.maximumWorld.z)
  12424. this.maximumWorld.z = v.z;
  12425. }
  12426. // Extend
  12427. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12428. this.extendSizeWorld.scaleInPlace(0.5);
  12429. // OBB
  12430. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12431. this.centerWorld.scaleInPlace(0.5);
  12432. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12433. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12434. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12435. this._worldMatrix = world;
  12436. };
  12437. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12438. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12439. };
  12440. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12441. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12442. };
  12443. BoundingBox.prototype.intersectsPoint = function (point) {
  12444. var delta = -BABYLON.Epsilon;
  12445. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12446. return false;
  12447. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12448. return false;
  12449. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12450. return false;
  12451. return true;
  12452. };
  12453. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12454. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12455. };
  12456. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12457. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12458. return false;
  12459. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12460. return false;
  12461. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12462. return false;
  12463. return true;
  12464. };
  12465. // Statics
  12466. BoundingBox.Intersects = function (box0, box1) {
  12467. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12468. return false;
  12469. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12470. return false;
  12471. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12472. return false;
  12473. return true;
  12474. };
  12475. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12476. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12477. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12478. return (num <= (sphereRadius * sphereRadius));
  12479. };
  12480. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12481. for (var p = 0; p < 6; p++) {
  12482. for (var i = 0; i < 8; i++) {
  12483. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12484. return false;
  12485. }
  12486. }
  12487. }
  12488. return true;
  12489. };
  12490. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12491. for (var p = 0; p < 6; p++) {
  12492. var inCount = 8;
  12493. for (var i = 0; i < 8; i++) {
  12494. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12495. --inCount;
  12496. }
  12497. else {
  12498. break;
  12499. }
  12500. }
  12501. if (inCount === 0)
  12502. return false;
  12503. }
  12504. return true;
  12505. };
  12506. return BoundingBox;
  12507. }());
  12508. BABYLON.BoundingBox = BoundingBox;
  12509. })(BABYLON || (BABYLON = {}));
  12510. //# sourceMappingURL=babylon.boundingBox.js.map
  12511. var BABYLON;
  12512. (function (BABYLON) {
  12513. var computeBoxExtents = function (axis, box) {
  12514. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12515. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12516. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12517. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12518. var r = r0 + r1 + r2;
  12519. return {
  12520. min: p - r,
  12521. max: p + r
  12522. };
  12523. };
  12524. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12525. var axisOverlap = function (axis, box0, box1) {
  12526. var result0 = computeBoxExtents(axis, box0);
  12527. var result1 = computeBoxExtents(axis, box1);
  12528. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12529. };
  12530. var BoundingInfo = /** @class */ (function () {
  12531. function BoundingInfo(minimum, maximum) {
  12532. this.minimum = minimum;
  12533. this.maximum = maximum;
  12534. this._isLocked = false;
  12535. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12536. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12537. }
  12538. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12539. get: function () {
  12540. return this._isLocked;
  12541. },
  12542. set: function (value) {
  12543. this._isLocked = value;
  12544. },
  12545. enumerable: true,
  12546. configurable: true
  12547. });
  12548. // Methods
  12549. BoundingInfo.prototype.update = function (world) {
  12550. if (this._isLocked) {
  12551. return;
  12552. }
  12553. this.boundingBox._update(world);
  12554. this.boundingSphere._update(world);
  12555. };
  12556. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12557. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12558. return false;
  12559. return this.boundingBox.isInFrustum(frustumPlanes);
  12560. };
  12561. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12562. /**
  12563. * Gets the world distance between the min and max points of the bounding box
  12564. */
  12565. get: function () {
  12566. var boundingBox = this.boundingBox;
  12567. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12568. return size.length();
  12569. },
  12570. enumerable: true,
  12571. configurable: true
  12572. });
  12573. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12574. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12575. };
  12576. BoundingInfo.prototype._checkCollision = function (collider) {
  12577. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12578. };
  12579. BoundingInfo.prototype.intersectsPoint = function (point) {
  12580. if (!this.boundingSphere.centerWorld) {
  12581. return false;
  12582. }
  12583. if (!this.boundingSphere.intersectsPoint(point)) {
  12584. return false;
  12585. }
  12586. if (!this.boundingBox.intersectsPoint(point)) {
  12587. return false;
  12588. }
  12589. return true;
  12590. };
  12591. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12592. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12593. return false;
  12594. }
  12595. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12596. return false;
  12597. }
  12598. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12599. return false;
  12600. }
  12601. if (!precise) {
  12602. return true;
  12603. }
  12604. var box0 = this.boundingBox;
  12605. var box1 = boundingInfo.boundingBox;
  12606. if (!axisOverlap(box0.directions[0], box0, box1))
  12607. return false;
  12608. if (!axisOverlap(box0.directions[1], box0, box1))
  12609. return false;
  12610. if (!axisOverlap(box0.directions[2], box0, box1))
  12611. return false;
  12612. if (!axisOverlap(box1.directions[0], box0, box1))
  12613. return false;
  12614. if (!axisOverlap(box1.directions[1], box0, box1))
  12615. return false;
  12616. if (!axisOverlap(box1.directions[2], box0, box1))
  12617. return false;
  12618. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12619. return false;
  12620. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12621. return false;
  12622. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12623. return false;
  12624. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12625. return false;
  12626. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12627. return false;
  12628. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12629. return false;
  12630. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12631. return false;
  12632. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12633. return false;
  12634. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12635. return false;
  12636. return true;
  12637. };
  12638. return BoundingInfo;
  12639. }());
  12640. BABYLON.BoundingInfo = BoundingInfo;
  12641. })(BABYLON || (BABYLON = {}));
  12642. //# sourceMappingURL=babylon.boundingInfo.js.map
  12643. var BABYLON;
  12644. (function (BABYLON) {
  12645. var AbstractMesh = /** @class */ (function (_super) {
  12646. __extends(AbstractMesh, _super);
  12647. // Constructor
  12648. function AbstractMesh(name, scene) {
  12649. if (scene === void 0) { scene = null; }
  12650. var _this = _super.call(this, name, scene) || this;
  12651. _this._facetNb = 0; // facet number
  12652. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12653. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12654. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12655. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12656. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12657. _this._subDiv = {
  12658. max: 1,
  12659. X: 1,
  12660. Y: 1,
  12661. Z: 1
  12662. };
  12663. // Normal matrix
  12664. _this._nonUniformScaling = false;
  12665. // Events
  12666. /**
  12667. * An event triggered when this mesh collides with another one
  12668. * @type {BABYLON.Observable}
  12669. */
  12670. _this.onCollideObservable = new BABYLON.Observable();
  12671. /**
  12672. * An event triggered when the collision's position changes
  12673. * @type {BABYLON.Observable}
  12674. */
  12675. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12676. /**
  12677. * An event triggered after the world matrix is updated
  12678. * @type {BABYLON.Observable}
  12679. */
  12680. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12681. /**
  12682. * An event triggered when material is changed
  12683. * @type {BABYLON.Observable}
  12684. */
  12685. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12686. // Properties
  12687. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12688. _this.position = BABYLON.Vector3.Zero();
  12689. /**
  12690. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12691. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12692. * or
  12693. * 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.
  12694. * for more info check WebGl documentations
  12695. */
  12696. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12697. /**
  12698. * 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:
  12699. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12700. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12701. * 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.
  12702. */
  12703. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12704. /**
  12705. * 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.
  12706. * The default value is -1 which means don't break the query and wait till the result.
  12707. */
  12708. _this.occlusionRetryCount = -1;
  12709. _this._occlusionInternalRetryCounter = 0;
  12710. _this._isOccluded = false;
  12711. _this._isOcclusionQueryInProgress = false;
  12712. _this._rotation = BABYLON.Vector3.Zero();
  12713. _this._scaling = BABYLON.Vector3.One();
  12714. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12715. _this.visibility = 1.0;
  12716. _this.alphaIndex = Number.MAX_VALUE;
  12717. _this.infiniteDistance = false;
  12718. _this.isVisible = true;
  12719. _this.isPickable = true;
  12720. _this.showBoundingBox = false;
  12721. _this.showSubMeshesBoundingBox = false;
  12722. _this.isBlocker = false;
  12723. _this.enablePointerMoveEvents = false;
  12724. _this.renderingGroupId = 0;
  12725. _this._receiveShadows = false;
  12726. _this.renderOutline = false;
  12727. _this.outlineColor = BABYLON.Color3.Red();
  12728. _this.outlineWidth = 0.02;
  12729. _this.renderOverlay = false;
  12730. _this.overlayColor = BABYLON.Color3.Red();
  12731. _this.overlayAlpha = 0.5;
  12732. _this._hasVertexAlpha = false;
  12733. _this._useVertexColors = true;
  12734. _this._computeBonesUsingShaders = true;
  12735. _this._numBoneInfluencers = 4;
  12736. _this._applyFog = true;
  12737. _this.scalingDeterminant = 1;
  12738. _this.useOctreeForRenderingSelection = true;
  12739. _this.useOctreeForPicking = true;
  12740. _this.useOctreeForCollisions = true;
  12741. _this._layerMask = 0x0FFFFFFF;
  12742. /**
  12743. * True if the mesh must be rendered in any case.
  12744. */
  12745. _this.alwaysSelectAsActiveMesh = false;
  12746. // Collisions
  12747. _this._checkCollisions = false;
  12748. _this._collisionMask = -1;
  12749. _this._collisionGroup = -1;
  12750. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12751. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12752. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12753. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12754. // Edges
  12755. _this.edgesWidth = 1;
  12756. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12757. // Cache
  12758. _this._localWorld = BABYLON.Matrix.Zero();
  12759. _this._worldMatrix = BABYLON.Matrix.Zero();
  12760. _this._absolutePosition = BABYLON.Vector3.Zero();
  12761. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12762. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12763. _this._isDirty = false;
  12764. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12765. _this._postMultiplyPivotMatrix = false;
  12766. _this._isDisposed = false;
  12767. _this._renderId = 0;
  12768. _this._intersectionsInProgress = new Array();
  12769. _this._isWorldMatrixFrozen = false;
  12770. _this._unIndexed = false;
  12771. _this._lightSources = new Array();
  12772. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12773. if (collidedMesh === void 0) { collidedMesh = null; }
  12774. //TODO move this to the collision coordinator!
  12775. if (_this.getScene().workerCollisions)
  12776. newPosition.multiplyInPlace(_this._collider.radius);
  12777. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12778. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12779. _this.position.addInPlace(_this._diffPositionForCollisions);
  12780. }
  12781. if (collidedMesh) {
  12782. _this.onCollideObservable.notifyObservers(collidedMesh);
  12783. }
  12784. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12785. };
  12786. _this.getScene().addMesh(_this);
  12787. _this._resyncLightSources();
  12788. return _this;
  12789. }
  12790. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12791. get: function () {
  12792. return AbstractMesh._BILLBOARDMODE_NONE;
  12793. },
  12794. enumerable: true,
  12795. configurable: true
  12796. });
  12797. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12798. get: function () {
  12799. return AbstractMesh._BILLBOARDMODE_X;
  12800. },
  12801. enumerable: true,
  12802. configurable: true
  12803. });
  12804. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12805. get: function () {
  12806. return AbstractMesh._BILLBOARDMODE_Y;
  12807. },
  12808. enumerable: true,
  12809. configurable: true
  12810. });
  12811. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12812. get: function () {
  12813. return AbstractMesh._BILLBOARDMODE_Z;
  12814. },
  12815. enumerable: true,
  12816. configurable: true
  12817. });
  12818. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12819. get: function () {
  12820. return AbstractMesh._BILLBOARDMODE_ALL;
  12821. },
  12822. enumerable: true,
  12823. configurable: true
  12824. });
  12825. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12826. /**
  12827. * Read-only : the number of facets in the mesh
  12828. */
  12829. get: function () {
  12830. return this._facetNb;
  12831. },
  12832. enumerable: true,
  12833. configurable: true
  12834. });
  12835. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12836. /**
  12837. * The number (integer) of subdivisions per axis in the partioning space
  12838. */
  12839. get: function () {
  12840. return this._partitioningSubdivisions;
  12841. },
  12842. set: function (nb) {
  12843. this._partitioningSubdivisions = nb;
  12844. },
  12845. enumerable: true,
  12846. configurable: true
  12847. });
  12848. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12849. /**
  12850. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12851. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12852. */
  12853. get: function () {
  12854. return this._partitioningBBoxRatio;
  12855. },
  12856. set: function (ratio) {
  12857. this._partitioningBBoxRatio = ratio;
  12858. },
  12859. enumerable: true,
  12860. configurable: true
  12861. });
  12862. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12863. /**
  12864. * Read-only boolean : is the feature facetData enabled ?
  12865. */
  12866. get: function () {
  12867. return this._facetDataEnabled;
  12868. },
  12869. enumerable: true,
  12870. configurable: true
  12871. });
  12872. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  12873. get: function () {
  12874. return this._nonUniformScaling;
  12875. },
  12876. set: function (value) {
  12877. if (this._nonUniformScaling === value) {
  12878. return;
  12879. }
  12880. this._nonUniformScaling = true;
  12881. this._markSubMeshesAsMiscDirty();
  12882. },
  12883. enumerable: true,
  12884. configurable: true
  12885. });
  12886. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12887. set: function (callback) {
  12888. if (this._onCollideObserver) {
  12889. this.onCollideObservable.remove(this._onCollideObserver);
  12890. }
  12891. this._onCollideObserver = this.onCollideObservable.add(callback);
  12892. },
  12893. enumerable: true,
  12894. configurable: true
  12895. });
  12896. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12897. set: function (callback) {
  12898. if (this._onCollisionPositionChangeObserver) {
  12899. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12900. }
  12901. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12902. },
  12903. enumerable: true,
  12904. configurable: true
  12905. });
  12906. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12907. /**
  12908. * 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.
  12909. */
  12910. get: function () {
  12911. return this._isOccluded;
  12912. },
  12913. set: function (value) {
  12914. this._isOccluded = value;
  12915. },
  12916. enumerable: true,
  12917. configurable: true
  12918. });
  12919. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12920. /**
  12921. * Flag to check the progress status of the query
  12922. */
  12923. get: function () {
  12924. return this._isOcclusionQueryInProgress;
  12925. },
  12926. enumerable: true,
  12927. configurable: true
  12928. });
  12929. Object.defineProperty(AbstractMesh.prototype, "material", {
  12930. get: function () {
  12931. return this._material;
  12932. },
  12933. set: function (value) {
  12934. if (this._material === value) {
  12935. return;
  12936. }
  12937. this._material = value;
  12938. if (this.onMaterialChangedObservable.hasObservers) {
  12939. this.onMaterialChangedObservable.notifyObservers(this);
  12940. }
  12941. if (!this.subMeshes) {
  12942. return;
  12943. }
  12944. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12945. var subMesh = _a[_i];
  12946. subMesh.setEffect(null);
  12947. }
  12948. },
  12949. enumerable: true,
  12950. configurable: true
  12951. });
  12952. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12953. get: function () {
  12954. return this._receiveShadows;
  12955. },
  12956. set: function (value) {
  12957. if (this._receiveShadows === value) {
  12958. return;
  12959. }
  12960. this._receiveShadows = value;
  12961. this._markSubMeshesAsLightDirty();
  12962. },
  12963. enumerable: true,
  12964. configurable: true
  12965. });
  12966. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12967. get: function () {
  12968. return this._hasVertexAlpha;
  12969. },
  12970. set: function (value) {
  12971. if (this._hasVertexAlpha === value) {
  12972. return;
  12973. }
  12974. this._hasVertexAlpha = value;
  12975. this._markSubMeshesAsAttributesDirty();
  12976. },
  12977. enumerable: true,
  12978. configurable: true
  12979. });
  12980. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12981. get: function () {
  12982. return this._useVertexColors;
  12983. },
  12984. set: function (value) {
  12985. if (this._useVertexColors === value) {
  12986. return;
  12987. }
  12988. this._useVertexColors = value;
  12989. this._markSubMeshesAsAttributesDirty();
  12990. },
  12991. enumerable: true,
  12992. configurable: true
  12993. });
  12994. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12995. get: function () {
  12996. return this._computeBonesUsingShaders;
  12997. },
  12998. set: function (value) {
  12999. if (this._computeBonesUsingShaders === value) {
  13000. return;
  13001. }
  13002. this._computeBonesUsingShaders = value;
  13003. this._markSubMeshesAsAttributesDirty();
  13004. },
  13005. enumerable: true,
  13006. configurable: true
  13007. });
  13008. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13009. get: function () {
  13010. return this._numBoneInfluencers;
  13011. },
  13012. set: function (value) {
  13013. if (this._numBoneInfluencers === value) {
  13014. return;
  13015. }
  13016. this._numBoneInfluencers = value;
  13017. this._markSubMeshesAsAttributesDirty();
  13018. },
  13019. enumerable: true,
  13020. configurable: true
  13021. });
  13022. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13023. get: function () {
  13024. return this._applyFog;
  13025. },
  13026. set: function (value) {
  13027. if (this._applyFog === value) {
  13028. return;
  13029. }
  13030. this._applyFog = value;
  13031. this._markSubMeshesAsMiscDirty();
  13032. },
  13033. enumerable: true,
  13034. configurable: true
  13035. });
  13036. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13037. get: function () {
  13038. return this._layerMask;
  13039. },
  13040. set: function (value) {
  13041. if (value === this._layerMask) {
  13042. return;
  13043. }
  13044. this._layerMask = value;
  13045. this._resyncLightSources();
  13046. },
  13047. enumerable: true,
  13048. configurable: true
  13049. });
  13050. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13051. get: function () {
  13052. return this._collisionMask;
  13053. },
  13054. set: function (mask) {
  13055. this._collisionMask = !isNaN(mask) ? mask : -1;
  13056. },
  13057. enumerable: true,
  13058. configurable: true
  13059. });
  13060. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13061. get: function () {
  13062. return this._collisionGroup;
  13063. },
  13064. set: function (mask) {
  13065. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13066. },
  13067. enumerable: true,
  13068. configurable: true
  13069. });
  13070. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13071. get: function () {
  13072. return null;
  13073. },
  13074. enumerable: true,
  13075. configurable: true
  13076. });
  13077. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13078. get: function () {
  13079. return this._skeleton;
  13080. },
  13081. set: function (value) {
  13082. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13083. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13084. }
  13085. if (value && value.needInitialSkinMatrix) {
  13086. value._registerMeshWithPoseMatrix(this);
  13087. }
  13088. this._skeleton = value;
  13089. if (!this._skeleton) {
  13090. this._bonesTransformMatrices = null;
  13091. }
  13092. this._markSubMeshesAsAttributesDirty();
  13093. },
  13094. enumerable: true,
  13095. configurable: true
  13096. });
  13097. /**
  13098. * Boolean : true if the mesh has been disposed.
  13099. */
  13100. AbstractMesh.prototype.isDisposed = function () {
  13101. return this._isDisposed;
  13102. };
  13103. /**
  13104. * Returns the string "AbstractMesh"
  13105. */
  13106. AbstractMesh.prototype.getClassName = function () {
  13107. return "AbstractMesh";
  13108. };
  13109. /**
  13110. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13111. */
  13112. AbstractMesh.prototype.toString = function (fullDetails) {
  13113. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13114. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13115. if (this._skeleton) {
  13116. ret += ", skeleton: " + this._skeleton.name;
  13117. }
  13118. if (fullDetails) {
  13119. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13120. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13121. }
  13122. return ret;
  13123. };
  13124. AbstractMesh.prototype._rebuild = function () {
  13125. if (this._occlusionQuery) {
  13126. this._occlusionQuery = null;
  13127. }
  13128. if (this._edgesRenderer) {
  13129. this._edgesRenderer._rebuild();
  13130. }
  13131. if (!this.subMeshes) {
  13132. return;
  13133. }
  13134. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13135. var subMesh = _a[_i];
  13136. subMesh._rebuild();
  13137. }
  13138. };
  13139. AbstractMesh.prototype._resyncLightSources = function () {
  13140. this._lightSources.length = 0;
  13141. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13142. var light = _a[_i];
  13143. if (!light.isEnabled()) {
  13144. continue;
  13145. }
  13146. if (light.canAffectMesh(this)) {
  13147. this._lightSources.push(light);
  13148. }
  13149. }
  13150. this._markSubMeshesAsLightDirty();
  13151. };
  13152. AbstractMesh.prototype._resyncLighSource = function (light) {
  13153. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13154. var index = this._lightSources.indexOf(light);
  13155. if (index === -1) {
  13156. if (!isIn) {
  13157. return;
  13158. }
  13159. this._lightSources.push(light);
  13160. }
  13161. else {
  13162. if (isIn) {
  13163. return;
  13164. }
  13165. this._lightSources.splice(index, 1);
  13166. }
  13167. this._markSubMeshesAsLightDirty();
  13168. };
  13169. AbstractMesh.prototype._removeLightSource = function (light) {
  13170. var index = this._lightSources.indexOf(light);
  13171. if (index === -1) {
  13172. return;
  13173. }
  13174. this._lightSources.splice(index, 1);
  13175. };
  13176. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13177. if (!this.subMeshes) {
  13178. return;
  13179. }
  13180. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13181. var subMesh = _a[_i];
  13182. if (subMesh._materialDefines) {
  13183. func(subMesh._materialDefines);
  13184. }
  13185. }
  13186. };
  13187. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13188. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13189. };
  13190. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13191. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13192. };
  13193. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13194. if (!this.subMeshes) {
  13195. return;
  13196. }
  13197. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13198. var subMesh = _a[_i];
  13199. var material = subMesh.getMaterial();
  13200. if (material) {
  13201. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13202. }
  13203. }
  13204. };
  13205. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13206. /**
  13207. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13208. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13209. * Default : (0.0, 0.0, 0.0)
  13210. */
  13211. get: function () {
  13212. return this._rotation;
  13213. },
  13214. set: function (newRotation) {
  13215. this._rotation = newRotation;
  13216. },
  13217. enumerable: true,
  13218. configurable: true
  13219. });
  13220. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13221. /**
  13222. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13223. * Default : (1.0, 1.0, 1.0)
  13224. */
  13225. get: function () {
  13226. return this._scaling;
  13227. },
  13228. set: function (newScaling) {
  13229. this._scaling = newScaling;
  13230. if (this.physicsImpostor) {
  13231. this.physicsImpostor.forceUpdate();
  13232. }
  13233. },
  13234. enumerable: true,
  13235. configurable: true
  13236. });
  13237. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13238. /**
  13239. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13240. * It's null by default.
  13241. * 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)
  13242. */
  13243. get: function () {
  13244. return this._rotationQuaternion;
  13245. },
  13246. set: function (quaternion) {
  13247. this._rotationQuaternion = quaternion;
  13248. //reset the rotation vector.
  13249. if (quaternion && this.rotation.length()) {
  13250. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13251. }
  13252. },
  13253. enumerable: true,
  13254. configurable: true
  13255. });
  13256. // Methods
  13257. /**
  13258. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13259. * Returns the AbstractMesh.
  13260. */
  13261. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13262. this._poseMatrix.copyFrom(matrix);
  13263. return this;
  13264. };
  13265. /**
  13266. * Returns the mesh Pose matrix.
  13267. * Returned object : Matrix
  13268. */
  13269. AbstractMesh.prototype.getPoseMatrix = function () {
  13270. return this._poseMatrix;
  13271. };
  13272. /**
  13273. * Disables the mesh edger rendering mode.
  13274. * Returns the AbstractMesh.
  13275. */
  13276. AbstractMesh.prototype.disableEdgesRendering = function () {
  13277. if (this._edgesRenderer) {
  13278. this._edgesRenderer.dispose();
  13279. this._edgesRenderer = null;
  13280. }
  13281. return this;
  13282. };
  13283. /**
  13284. * Enables the edge rendering mode on the mesh.
  13285. * This mode makes the mesh edges visible.
  13286. * Returns the AbstractMesh.
  13287. */
  13288. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13289. if (epsilon === void 0) { epsilon = 0.95; }
  13290. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13291. this.disableEdgesRendering();
  13292. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13293. return this;
  13294. };
  13295. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13296. /**
  13297. * Returns true if the mesh is blocked. Used by the class Mesh.
  13298. * Returns the boolean `false` by default.
  13299. */
  13300. get: function () {
  13301. return false;
  13302. },
  13303. enumerable: true,
  13304. configurable: true
  13305. });
  13306. /**
  13307. * Returns the mesh itself by default, used by the class Mesh.
  13308. * Returned type : AbstractMesh
  13309. */
  13310. AbstractMesh.prototype.getLOD = function (camera) {
  13311. return this;
  13312. };
  13313. /**
  13314. * Returns 0 by default, used by the class Mesh.
  13315. * Returns an integer.
  13316. */
  13317. AbstractMesh.prototype.getTotalVertices = function () {
  13318. return 0;
  13319. };
  13320. /**
  13321. * Returns null by default, used by the class Mesh.
  13322. * Returned type : integer array
  13323. */
  13324. AbstractMesh.prototype.getIndices = function () {
  13325. return null;
  13326. };
  13327. /**
  13328. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13329. * Returned type : float array or Float32Array
  13330. */
  13331. AbstractMesh.prototype.getVerticesData = function (kind) {
  13332. return null;
  13333. };
  13334. /**
  13335. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13336. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13337. * The `data` are either a numeric array either a Float32Array.
  13338. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13339. * 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).
  13340. * Note that a new underlying VertexBuffer object is created each call.
  13341. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13342. *
  13343. * Possible `kind` values :
  13344. * - BABYLON.VertexBuffer.PositionKind
  13345. * - BABYLON.VertexBuffer.UVKind
  13346. * - BABYLON.VertexBuffer.UV2Kind
  13347. * - BABYLON.VertexBuffer.UV3Kind
  13348. * - BABYLON.VertexBuffer.UV4Kind
  13349. * - BABYLON.VertexBuffer.UV5Kind
  13350. * - BABYLON.VertexBuffer.UV6Kind
  13351. * - BABYLON.VertexBuffer.ColorKind
  13352. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13353. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13354. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13355. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13356. *
  13357. * Returns the Mesh.
  13358. */
  13359. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13360. return this;
  13361. };
  13362. /**
  13363. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13364. * If the mesh has no geometry, it is simply returned as it is.
  13365. * The `data` are either a numeric array either a Float32Array.
  13366. * No new underlying VertexBuffer object is created.
  13367. * 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.
  13368. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13369. *
  13370. * Possible `kind` values :
  13371. * - BABYLON.VertexBuffer.PositionKind
  13372. * - BABYLON.VertexBuffer.UVKind
  13373. * - BABYLON.VertexBuffer.UV2Kind
  13374. * - BABYLON.VertexBuffer.UV3Kind
  13375. * - BABYLON.VertexBuffer.UV4Kind
  13376. * - BABYLON.VertexBuffer.UV5Kind
  13377. * - BABYLON.VertexBuffer.UV6Kind
  13378. * - BABYLON.VertexBuffer.ColorKind
  13379. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13380. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13381. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13382. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13383. *
  13384. * Returns the Mesh.
  13385. */
  13386. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13387. return this;
  13388. };
  13389. /**
  13390. * Sets the mesh indices.
  13391. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13392. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13393. * This method creates a new index buffer each call.
  13394. * Returns the Mesh.
  13395. */
  13396. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13397. return this;
  13398. };
  13399. /** Returns false by default, used by the class Mesh.
  13400. * Returns a boolean
  13401. */
  13402. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13403. return false;
  13404. };
  13405. /**
  13406. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13407. * Returns a BoundingInfo
  13408. */
  13409. AbstractMesh.prototype.getBoundingInfo = function () {
  13410. if (this._masterMesh) {
  13411. return this._masterMesh.getBoundingInfo();
  13412. }
  13413. if (!this._boundingInfo) {
  13414. this._updateBoundingInfo();
  13415. }
  13416. return this._boundingInfo;
  13417. };
  13418. /**
  13419. * Sets a mesh new object BoundingInfo.
  13420. * Returns the AbstractMesh.
  13421. */
  13422. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13423. this._boundingInfo = boundingInfo;
  13424. return this;
  13425. };
  13426. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13427. get: function () {
  13428. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13429. },
  13430. enumerable: true,
  13431. configurable: true
  13432. });
  13433. AbstractMesh.prototype._preActivate = function () {
  13434. };
  13435. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13436. };
  13437. AbstractMesh.prototype._activate = function (renderId) {
  13438. this._renderId = renderId;
  13439. };
  13440. /**
  13441. * Returns the last update of the World matrix
  13442. * Returns a Matrix.
  13443. */
  13444. AbstractMesh.prototype.getWorldMatrix = function () {
  13445. if (this._masterMesh) {
  13446. return this._masterMesh.getWorldMatrix();
  13447. }
  13448. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13449. this.computeWorldMatrix();
  13450. }
  13451. return this._worldMatrix;
  13452. };
  13453. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13454. /**
  13455. * Returns directly the last state of the mesh World matrix.
  13456. * A Matrix is returned.
  13457. */
  13458. get: function () {
  13459. return this._worldMatrix;
  13460. },
  13461. enumerable: true,
  13462. configurable: true
  13463. });
  13464. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13465. /**
  13466. * Returns the current mesh absolute position.
  13467. * Retuns a Vector3.
  13468. */
  13469. get: function () {
  13470. return this._absolutePosition;
  13471. },
  13472. enumerable: true,
  13473. configurable: true
  13474. });
  13475. /**
  13476. * Prevents the World matrix to be computed any longer.
  13477. * Returns the AbstractMesh.
  13478. */
  13479. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13480. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13481. this.computeWorldMatrix(true);
  13482. this._isWorldMatrixFrozen = true;
  13483. return this;
  13484. };
  13485. /**
  13486. * Allows back the World matrix computation.
  13487. * Returns the AbstractMesh.
  13488. */
  13489. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13490. this._isWorldMatrixFrozen = false;
  13491. this.computeWorldMatrix(true);
  13492. return this;
  13493. };
  13494. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13495. /**
  13496. * True if the World matrix has been frozen.
  13497. * Returns a boolean.
  13498. */
  13499. get: function () {
  13500. return this._isWorldMatrixFrozen;
  13501. },
  13502. enumerable: true,
  13503. configurable: true
  13504. });
  13505. /**
  13506. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13507. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13508. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13509. * The passed axis is also normalized.
  13510. * Returns the AbstractMesh.
  13511. */
  13512. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13513. axis.normalize();
  13514. if (!this.rotationQuaternion) {
  13515. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13516. this.rotation = BABYLON.Vector3.Zero();
  13517. }
  13518. var rotationQuaternion;
  13519. if (!space || space === BABYLON.Space.LOCAL) {
  13520. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13521. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13522. }
  13523. else {
  13524. if (this.parent) {
  13525. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13526. invertParentWorldMatrix.invert();
  13527. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13528. }
  13529. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13530. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13531. }
  13532. return this;
  13533. };
  13534. /**
  13535. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13536. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13537. * The passed axis is also normalized.
  13538. * Returns the AbstractMesh.
  13539. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13540. */
  13541. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13542. axis.normalize();
  13543. if (!this.rotationQuaternion) {
  13544. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13545. this.rotation.copyFromFloats(0, 0, 0);
  13546. }
  13547. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13548. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13549. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13550. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13551. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13552. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13553. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13554. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13555. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13556. return this;
  13557. };
  13558. /**
  13559. * Translates the mesh along the axis vector for the passed distance in the given space.
  13560. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13561. * Returns the AbstractMesh.
  13562. */
  13563. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13564. var displacementVector = axis.scale(distance);
  13565. if (!space || space === BABYLON.Space.LOCAL) {
  13566. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13567. this.setPositionWithLocalVector(tempV3);
  13568. }
  13569. else {
  13570. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13571. }
  13572. return this;
  13573. };
  13574. /**
  13575. * Adds a rotation step to the mesh current rotation.
  13576. * x, y, z are Euler angles expressed in radians.
  13577. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13578. * This means this rotation is made in the mesh local space only.
  13579. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13580. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13581. * ```javascript
  13582. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13583. * ```
  13584. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13585. * 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.
  13586. * Returns the AbstractMesh.
  13587. */
  13588. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13589. var rotationQuaternion;
  13590. if (this.rotationQuaternion) {
  13591. rotationQuaternion = this.rotationQuaternion;
  13592. }
  13593. else {
  13594. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13595. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13596. }
  13597. var accumulation = BABYLON.Tmp.Quaternion[0];
  13598. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13599. rotationQuaternion.multiplyInPlace(accumulation);
  13600. if (!this.rotationQuaternion) {
  13601. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13602. }
  13603. return this;
  13604. };
  13605. /**
  13606. * Retuns the mesh absolute position in the World.
  13607. * Returns a Vector3.
  13608. */
  13609. AbstractMesh.prototype.getAbsolutePosition = function () {
  13610. this.computeWorldMatrix();
  13611. return this._absolutePosition;
  13612. };
  13613. /**
  13614. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13615. * Returns the AbstractMesh.
  13616. */
  13617. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13618. if (!absolutePosition) {
  13619. return this;
  13620. }
  13621. var absolutePositionX;
  13622. var absolutePositionY;
  13623. var absolutePositionZ;
  13624. if (absolutePosition.x === undefined) {
  13625. if (arguments.length < 3) {
  13626. return this;
  13627. }
  13628. absolutePositionX = arguments[0];
  13629. absolutePositionY = arguments[1];
  13630. absolutePositionZ = arguments[2];
  13631. }
  13632. else {
  13633. absolutePositionX = absolutePosition.x;
  13634. absolutePositionY = absolutePosition.y;
  13635. absolutePositionZ = absolutePosition.z;
  13636. }
  13637. if (this.parent) {
  13638. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13639. invertParentWorldMatrix.invert();
  13640. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13641. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13642. }
  13643. else {
  13644. this.position.x = absolutePositionX;
  13645. this.position.y = absolutePositionY;
  13646. this.position.z = absolutePositionZ;
  13647. }
  13648. return this;
  13649. };
  13650. // ================================== Point of View Movement =================================
  13651. /**
  13652. * Perform relative position change from the point of view of behind the front of the mesh.
  13653. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13654. * Supports definition of mesh facing forward or backward.
  13655. * @param {number} amountRight
  13656. * @param {number} amountUp
  13657. * @param {number} amountForward
  13658. *
  13659. * Returns the AbstractMesh.
  13660. */
  13661. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13662. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13663. return this;
  13664. };
  13665. /**
  13666. * Calculate relative position change from the point of view of behind the front of the mesh.
  13667. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13668. * Supports definition of mesh facing forward or backward.
  13669. * @param {number} amountRight
  13670. * @param {number} amountUp
  13671. * @param {number} amountForward
  13672. *
  13673. * Returns a new Vector3.
  13674. */
  13675. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13676. var rotMatrix = new BABYLON.Matrix();
  13677. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13678. rotQuaternion.toRotationMatrix(rotMatrix);
  13679. var translationDelta = BABYLON.Vector3.Zero();
  13680. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13681. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13682. return translationDelta;
  13683. };
  13684. // ================================== Point of View Rotation =================================
  13685. /**
  13686. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13687. * Supports definition of mesh facing forward or backward.
  13688. * @param {number} flipBack
  13689. * @param {number} twirlClockwise
  13690. * @param {number} tiltRight
  13691. *
  13692. * Returns the AbstractMesh.
  13693. */
  13694. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13695. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13696. return this;
  13697. };
  13698. /**
  13699. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13700. * Supports definition of mesh facing forward or backward.
  13701. * @param {number} flipBack
  13702. * @param {number} twirlClockwise
  13703. * @param {number} tiltRight
  13704. *
  13705. * Returns a new Vector3.
  13706. */
  13707. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13708. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13709. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13710. };
  13711. /**
  13712. * Sets a new pivot matrix to the mesh.
  13713. * Returns the AbstractMesh.
  13714. */
  13715. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13716. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13717. this._pivotMatrix = matrix.clone();
  13718. this._cache.pivotMatrixUpdated = true;
  13719. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13720. if (this._postMultiplyPivotMatrix) {
  13721. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13722. }
  13723. return this;
  13724. };
  13725. /**
  13726. * Returns the mesh pivot matrix.
  13727. * Default : Identity.
  13728. * A Matrix is returned.
  13729. */
  13730. AbstractMesh.prototype.getPivotMatrix = function () {
  13731. return this._pivotMatrix;
  13732. };
  13733. AbstractMesh.prototype._isSynchronized = function () {
  13734. if (this._isDirty) {
  13735. return false;
  13736. }
  13737. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13738. return false;
  13739. if (this._cache.pivotMatrixUpdated) {
  13740. return false;
  13741. }
  13742. if (this.infiniteDistance) {
  13743. return false;
  13744. }
  13745. if (!this._cache.position.equals(this.position))
  13746. return false;
  13747. if (this.rotationQuaternion) {
  13748. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13749. return false;
  13750. }
  13751. if (!this._cache.rotation.equals(this.rotation))
  13752. return false;
  13753. if (!this._cache.scaling.equals(this.scaling))
  13754. return false;
  13755. return true;
  13756. };
  13757. AbstractMesh.prototype._initCache = function () {
  13758. _super.prototype._initCache.call(this);
  13759. this._cache.localMatrixUpdated = false;
  13760. this._cache.position = BABYLON.Vector3.Zero();
  13761. this._cache.scaling = BABYLON.Vector3.Zero();
  13762. this._cache.rotation = BABYLON.Vector3.Zero();
  13763. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13764. this._cache.billboardMode = -1;
  13765. };
  13766. AbstractMesh.prototype.markAsDirty = function (property) {
  13767. if (property === "rotation") {
  13768. this.rotationQuaternion = null;
  13769. }
  13770. this._currentRenderId = Number.MAX_VALUE;
  13771. this._isDirty = true;
  13772. return this;
  13773. };
  13774. /**
  13775. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13776. */
  13777. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13778. this.computeWorldMatrix(true);
  13779. var min;
  13780. var max;
  13781. var boundingInfo = this.getBoundingInfo();
  13782. if (!this.subMeshes || !boundingInfo) {
  13783. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13784. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13785. }
  13786. else {
  13787. min = boundingInfo.boundingBox.minimumWorld;
  13788. max = boundingInfo.boundingBox.maximumWorld;
  13789. }
  13790. var descendants = this.getDescendants(false);
  13791. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13792. var descendant = descendants_1[_i];
  13793. var childMesh = descendant;
  13794. childMesh.computeWorldMatrix(true);
  13795. var childBoundingInfo = childMesh.getBoundingInfo();
  13796. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  13797. continue;
  13798. }
  13799. var boundingBox = childBoundingInfo.boundingBox;
  13800. var minBox = boundingBox.minimumWorld;
  13801. var maxBox = boundingBox.maximumWorld;
  13802. BABYLON.Tools.CheckExtends(minBox, min, max);
  13803. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13804. }
  13805. return {
  13806. min: min,
  13807. max: max
  13808. };
  13809. };
  13810. /**
  13811. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13812. * Returns the AbstractMesh.
  13813. */
  13814. AbstractMesh.prototype._updateBoundingInfo = function () {
  13815. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13816. this._boundingInfo.update(this.worldMatrixFromCache);
  13817. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13818. return this;
  13819. };
  13820. /**
  13821. * Update a mesh's children BoundingInfo objects only.
  13822. * Returns the AbstractMesh.
  13823. */
  13824. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13825. if (!this.subMeshes) {
  13826. return this;
  13827. }
  13828. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13829. var subMesh = this.subMeshes[subIndex];
  13830. if (!subMesh.IsGlobal) {
  13831. subMesh.updateBoundingInfo(matrix);
  13832. }
  13833. }
  13834. return this;
  13835. };
  13836. /**
  13837. * Computes the mesh World matrix and returns it.
  13838. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13839. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13840. * If the parameter `force`is set to `true`, the actual computation is done.
  13841. * Returns the mesh World Matrix.
  13842. */
  13843. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13844. if (this._isWorldMatrixFrozen) {
  13845. return this._worldMatrix;
  13846. }
  13847. if (!force && this.isSynchronized(true)) {
  13848. this._currentRenderId = this.getScene().getRenderId();
  13849. return this._worldMatrix;
  13850. }
  13851. this._cache.position.copyFrom(this.position);
  13852. this._cache.scaling.copyFrom(this.scaling);
  13853. this._cache.pivotMatrixUpdated = false;
  13854. this._cache.billboardMode = this.billboardMode;
  13855. this._currentRenderId = this.getScene().getRenderId();
  13856. this._isDirty = false;
  13857. // Scaling
  13858. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13859. // Rotation
  13860. //rotate, if quaternion is set and rotation was used
  13861. if (this.rotationQuaternion) {
  13862. var len = this.rotation.length();
  13863. if (len) {
  13864. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13865. this.rotation.copyFromFloats(0, 0, 0);
  13866. }
  13867. }
  13868. if (this.rotationQuaternion) {
  13869. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13870. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13871. }
  13872. else {
  13873. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13874. this._cache.rotation.copyFrom(this.rotation);
  13875. }
  13876. // Translation
  13877. var camera = this.getScene().activeCamera;
  13878. if (this.infiniteDistance && !this.parent && camera) {
  13879. var cameraWorldMatrix = camera.getWorldMatrix();
  13880. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13881. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13882. }
  13883. else {
  13884. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13885. }
  13886. // Composing transformations
  13887. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13888. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13889. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13890. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13891. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13892. // Need to decompose each rotation here
  13893. var currentPosition = BABYLON.Tmp.Vector3[3];
  13894. if (this.parent && this.parent.getWorldMatrix) {
  13895. if (this._meshToBoneReferal) {
  13896. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13897. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13898. }
  13899. else {
  13900. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13901. }
  13902. }
  13903. else {
  13904. currentPosition.copyFrom(this.position);
  13905. }
  13906. currentPosition.subtractInPlace(camera.globalPosition);
  13907. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13908. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13909. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13910. }
  13911. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13912. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13913. }
  13914. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13915. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13916. }
  13917. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13918. }
  13919. else {
  13920. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13921. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13922. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13923. }
  13924. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13925. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13926. }
  13927. // Local world
  13928. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13929. // Parent
  13930. if (this.parent && this.parent.getWorldMatrix) {
  13931. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13932. if (this._meshToBoneReferal) {
  13933. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13934. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13935. }
  13936. else {
  13937. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13938. }
  13939. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13940. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13941. this._worldMatrix.copyFrom(this._localWorld);
  13942. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13943. }
  13944. else {
  13945. if (this._meshToBoneReferal) {
  13946. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13947. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13948. }
  13949. else {
  13950. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13951. }
  13952. }
  13953. this._markSyncedWithParent();
  13954. }
  13955. else {
  13956. this._worldMatrix.copyFrom(this._localWorld);
  13957. }
  13958. // Post multiply inverse of pivotMatrix
  13959. if (this._postMultiplyPivotMatrix) {
  13960. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13961. }
  13962. // Normal matrix
  13963. if (this.scaling.isNonUniform) {
  13964. this.nonUniformScaling = true;
  13965. }
  13966. else if (this.parent && this.parent._nonUniformScaling) {
  13967. this.nonUniformScaling = this.parent._nonUniformScaling;
  13968. }
  13969. else {
  13970. this.nonUniformScaling = false;
  13971. }
  13972. // Bounding info
  13973. this._updateBoundingInfo();
  13974. // Absolute position
  13975. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13976. // Callbacks
  13977. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13978. if (!this._poseMatrix) {
  13979. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13980. }
  13981. return this._worldMatrix;
  13982. };
  13983. /**
  13984. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13985. * @param func: callback function to add
  13986. *
  13987. * Returns the AbstractMesh.
  13988. */
  13989. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13990. this.onAfterWorldMatrixUpdateObservable.add(func);
  13991. return this;
  13992. };
  13993. /**
  13994. * Removes a registered callback function.
  13995. * Returns the AbstractMesh.
  13996. */
  13997. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13998. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13999. return this;
  14000. };
  14001. /**
  14002. * Sets the mesh position in its local space.
  14003. * Returns the AbstractMesh.
  14004. */
  14005. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14006. this.computeWorldMatrix();
  14007. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14008. return this;
  14009. };
  14010. /**
  14011. * Returns the mesh position in the local space from the current World matrix values.
  14012. * Returns a new Vector3.
  14013. */
  14014. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14015. this.computeWorldMatrix();
  14016. var invLocalWorldMatrix = this._localWorld.clone();
  14017. invLocalWorldMatrix.invert();
  14018. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14019. };
  14020. /**
  14021. * Translates the mesh along the passed Vector3 in its local space.
  14022. * Returns the AbstractMesh.
  14023. */
  14024. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14025. this.computeWorldMatrix(true);
  14026. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14027. return this;
  14028. };
  14029. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14030. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14031. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14032. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14033. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14034. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14035. /// <returns>Mesh oriented towards targetMesh</returns>
  14036. if (yawCor === void 0) { yawCor = 0; }
  14037. if (pitchCor === void 0) { pitchCor = 0; }
  14038. if (rollCor === void 0) { rollCor = 0; }
  14039. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14040. var dv = AbstractMesh._lookAtVectorCache;
  14041. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14042. targetPoint.subtractToRef(pos, dv);
  14043. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14044. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14045. var pitch = Math.atan2(dv.y, len);
  14046. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14047. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14048. return this;
  14049. };
  14050. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14051. this._meshToBoneReferal = affectedMesh;
  14052. this.parent = bone;
  14053. if (bone.getWorldMatrix().determinant() < 0) {
  14054. this.scalingDeterminant *= -1;
  14055. }
  14056. return this;
  14057. };
  14058. AbstractMesh.prototype.detachFromBone = function () {
  14059. if (!this.parent) {
  14060. return this;
  14061. }
  14062. if (this.parent.getWorldMatrix().determinant() < 0) {
  14063. this.scalingDeterminant *= -1;
  14064. }
  14065. this._meshToBoneReferal = null;
  14066. this.parent = null;
  14067. return this;
  14068. };
  14069. /**
  14070. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14071. * A mesh is in the frustum if its bounding box intersects the frustum.
  14072. * Boolean returned.
  14073. */
  14074. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14075. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14076. };
  14077. /**
  14078. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14079. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14080. * Boolean returned.
  14081. */
  14082. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14083. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14084. ;
  14085. };
  14086. /**
  14087. * True if the mesh intersects another mesh or a SolidParticle object.
  14088. * 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)
  14089. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14090. * Returns a boolean.
  14091. */
  14092. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14093. if (precise === void 0) { precise = false; }
  14094. if (!this._boundingInfo || !mesh._boundingInfo) {
  14095. return false;
  14096. }
  14097. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14098. return true;
  14099. }
  14100. if (includeDescendants) {
  14101. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14102. var child = _a[_i];
  14103. if (child.intersectsMesh(mesh, precise, true)) {
  14104. return true;
  14105. }
  14106. }
  14107. }
  14108. return false;
  14109. };
  14110. /**
  14111. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14112. * Returns a boolean.
  14113. */
  14114. AbstractMesh.prototype.intersectsPoint = function (point) {
  14115. if (!this._boundingInfo) {
  14116. return false;
  14117. }
  14118. return this._boundingInfo.intersectsPoint(point);
  14119. };
  14120. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14121. return this.physicsImpostor;
  14122. };
  14123. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14124. if (camera === void 0) { camera = null; }
  14125. if (!camera) {
  14126. camera = this.getScene().activeCamera;
  14127. }
  14128. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14129. };
  14130. /**
  14131. * Returns the distance from the mesh to the active camera.
  14132. * Returns a float.
  14133. */
  14134. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14135. if (camera === void 0) { camera = null; }
  14136. if (!camera) {
  14137. camera = this.getScene().activeCamera;
  14138. }
  14139. return this.absolutePosition.subtract(camera.position).length();
  14140. };
  14141. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14142. if (!this.physicsImpostor) {
  14143. return this;
  14144. }
  14145. this.physicsImpostor.applyImpulse(force, contactPoint);
  14146. return this;
  14147. };
  14148. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14149. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14150. return this;
  14151. }
  14152. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14153. mainPivot: pivot1,
  14154. connectedPivot: pivot2,
  14155. nativeParams: options
  14156. });
  14157. return this;
  14158. };
  14159. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14160. // Collisions
  14161. /**
  14162. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14163. * Default `false`.
  14164. */
  14165. get: function () {
  14166. return this._checkCollisions;
  14167. },
  14168. set: function (collisionEnabled) {
  14169. this._checkCollisions = collisionEnabled;
  14170. if (this.getScene().workerCollisions) {
  14171. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14172. }
  14173. },
  14174. enumerable: true,
  14175. configurable: true
  14176. });
  14177. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14178. var globalPosition = this.getAbsolutePosition();
  14179. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14180. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14181. if (!this._collider) {
  14182. this._collider = new BABYLON.Collider();
  14183. }
  14184. this._collider.radius = this.ellipsoid;
  14185. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14186. return this;
  14187. };
  14188. // Submeshes octree
  14189. /**
  14190. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14191. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14192. * Returns an Octree of submeshes.
  14193. */
  14194. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14195. if (maxCapacity === void 0) { maxCapacity = 64; }
  14196. if (maxDepth === void 0) { maxDepth = 2; }
  14197. if (!this._submeshesOctree) {
  14198. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14199. }
  14200. this.computeWorldMatrix(true);
  14201. var boundingInfo = this.getBoundingInfo();
  14202. // Update octree
  14203. if (boundingInfo) {
  14204. var bbox = boundingInfo.boundingBox;
  14205. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14206. }
  14207. return this._submeshesOctree;
  14208. };
  14209. // Collisions
  14210. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14211. this._generatePointsArray();
  14212. if (!this._positions) {
  14213. return this;
  14214. }
  14215. // Transformation
  14216. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14217. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14218. subMesh._lastColliderWorldVertices = [];
  14219. subMesh._trianglePlanes = [];
  14220. var start = subMesh.verticesStart;
  14221. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14222. for (var i = start; i < end; i++) {
  14223. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14224. }
  14225. }
  14226. // Collide
  14227. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14228. if (collider.collisionFound) {
  14229. collider.collidedMesh = this;
  14230. }
  14231. return this;
  14232. };
  14233. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14234. var subMeshes;
  14235. var len;
  14236. // Octrees
  14237. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14238. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14239. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14240. len = intersections.length;
  14241. subMeshes = intersections.data;
  14242. }
  14243. else {
  14244. subMeshes = this.subMeshes;
  14245. len = subMeshes.length;
  14246. }
  14247. for (var index = 0; index < len; index++) {
  14248. var subMesh = subMeshes[index];
  14249. // Bounding test
  14250. if (len > 1 && !subMesh._checkCollision(collider))
  14251. continue;
  14252. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14253. }
  14254. return this;
  14255. };
  14256. AbstractMesh.prototype._checkCollision = function (collider) {
  14257. // Bounding box test
  14258. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14259. return this;
  14260. // Transformation matrix
  14261. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14262. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14263. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14264. return this;
  14265. };
  14266. // Picking
  14267. AbstractMesh.prototype._generatePointsArray = function () {
  14268. return false;
  14269. };
  14270. /**
  14271. * Checks if the passed Ray intersects with the mesh.
  14272. * Returns an object PickingInfo.
  14273. */
  14274. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14275. var pickingInfo = new BABYLON.PickingInfo();
  14276. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14277. return pickingInfo;
  14278. }
  14279. if (!this._generatePointsArray()) {
  14280. return pickingInfo;
  14281. }
  14282. var intersectInfo = null;
  14283. // Octrees
  14284. var subMeshes;
  14285. var len;
  14286. if (this._submeshesOctree && this.useOctreeForPicking) {
  14287. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14288. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14289. len = intersections.length;
  14290. subMeshes = intersections.data;
  14291. }
  14292. else {
  14293. subMeshes = this.subMeshes;
  14294. len = subMeshes.length;
  14295. }
  14296. for (var index = 0; index < len; index++) {
  14297. var subMesh = subMeshes[index];
  14298. // Bounding test
  14299. if (len > 1 && !subMesh.canIntersects(ray))
  14300. continue;
  14301. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14302. if (currentIntersectInfo) {
  14303. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14304. intersectInfo = currentIntersectInfo;
  14305. intersectInfo.subMeshId = index;
  14306. if (fastCheck) {
  14307. break;
  14308. }
  14309. }
  14310. }
  14311. }
  14312. if (intersectInfo) {
  14313. // Get picked point
  14314. var world = this.getWorldMatrix();
  14315. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14316. var direction = ray.direction.clone();
  14317. direction = direction.scale(intersectInfo.distance);
  14318. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14319. var pickedPoint = worldOrigin.add(worldDirection);
  14320. // Return result
  14321. pickingInfo.hit = true;
  14322. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14323. pickingInfo.pickedPoint = pickedPoint;
  14324. pickingInfo.pickedMesh = this;
  14325. pickingInfo.bu = intersectInfo.bu || 0;
  14326. pickingInfo.bv = intersectInfo.bv || 0;
  14327. pickingInfo.faceId = intersectInfo.faceId;
  14328. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14329. return pickingInfo;
  14330. }
  14331. return pickingInfo;
  14332. };
  14333. /**
  14334. * Clones the mesh, used by the class Mesh.
  14335. * Just returns `null` for an AbstractMesh.
  14336. */
  14337. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14338. return null;
  14339. };
  14340. /**
  14341. * Disposes all the mesh submeshes.
  14342. * Returns the AbstractMesh.
  14343. */
  14344. AbstractMesh.prototype.releaseSubMeshes = function () {
  14345. if (this.subMeshes) {
  14346. while (this.subMeshes.length) {
  14347. this.subMeshes[0].dispose();
  14348. }
  14349. }
  14350. else {
  14351. this.subMeshes = new Array();
  14352. }
  14353. return this;
  14354. };
  14355. /**
  14356. * Disposes the AbstractMesh.
  14357. * Some internal references are kept for further use.
  14358. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14359. * Returns nothing.
  14360. */
  14361. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14362. var _this = this;
  14363. var index;
  14364. // Action manager
  14365. if (this.actionManager) {
  14366. this.actionManager.dispose();
  14367. this.actionManager = null;
  14368. }
  14369. // Skeleton
  14370. this.skeleton = null;
  14371. // Animations
  14372. this.getScene().stopAnimation(this);
  14373. // Physics
  14374. if (this.physicsImpostor) {
  14375. this.physicsImpostor.dispose();
  14376. }
  14377. // Intersections in progress
  14378. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14379. var other = this._intersectionsInProgress[index];
  14380. var pos = other._intersectionsInProgress.indexOf(this);
  14381. other._intersectionsInProgress.splice(pos, 1);
  14382. }
  14383. this._intersectionsInProgress = [];
  14384. // Lights
  14385. var lights = this.getScene().lights;
  14386. lights.forEach(function (light) {
  14387. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14388. if (meshIndex !== -1) {
  14389. light.includedOnlyMeshes.splice(meshIndex, 1);
  14390. }
  14391. meshIndex = light.excludedMeshes.indexOf(_this);
  14392. if (meshIndex !== -1) {
  14393. light.excludedMeshes.splice(meshIndex, 1);
  14394. }
  14395. // Shadow generators
  14396. var generator = light.getShadowGenerator();
  14397. if (generator) {
  14398. var shadowMap = generator.getShadowMap();
  14399. if (shadowMap && shadowMap.renderList) {
  14400. meshIndex = shadowMap.renderList.indexOf(_this);
  14401. if (meshIndex !== -1) {
  14402. shadowMap.renderList.splice(meshIndex, 1);
  14403. }
  14404. }
  14405. }
  14406. });
  14407. // Edges
  14408. if (this._edgesRenderer) {
  14409. this._edgesRenderer.dispose();
  14410. this._edgesRenderer = null;
  14411. }
  14412. // SubMeshes
  14413. if (this.getClassName() !== "InstancedMesh") {
  14414. this.releaseSubMeshes();
  14415. }
  14416. // Octree
  14417. var sceneOctree = this.getScene().selectionOctree;
  14418. if (sceneOctree) {
  14419. var index = sceneOctree.dynamicContent.indexOf(this);
  14420. if (index !== -1) {
  14421. sceneOctree.dynamicContent.splice(index, 1);
  14422. }
  14423. }
  14424. // Query
  14425. var engine = this.getScene().getEngine();
  14426. if (this._occlusionQuery) {
  14427. this._isOcclusionQueryInProgress = false;
  14428. engine.deleteQuery(this._occlusionQuery);
  14429. this._occlusionQuery = null;
  14430. }
  14431. // Engine
  14432. engine.wipeCaches();
  14433. // Remove from scene
  14434. this.getScene().removeMesh(this);
  14435. if (!doNotRecurse) {
  14436. // Particles
  14437. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14438. if (this.getScene().particleSystems[index].emitter === this) {
  14439. this.getScene().particleSystems[index].dispose();
  14440. index--;
  14441. }
  14442. }
  14443. // Children
  14444. var objects = this.getDescendants(true);
  14445. for (index = 0; index < objects.length; index++) {
  14446. objects[index].dispose();
  14447. }
  14448. }
  14449. else {
  14450. var childMeshes = this.getChildMeshes(true);
  14451. for (index = 0; index < childMeshes.length; index++) {
  14452. var child = childMeshes[index];
  14453. child.parent = null;
  14454. child.computeWorldMatrix(true);
  14455. }
  14456. }
  14457. // facet data
  14458. if (this._facetDataEnabled) {
  14459. this.disableFacetData();
  14460. }
  14461. this.onAfterWorldMatrixUpdateObservable.clear();
  14462. this.onCollideObservable.clear();
  14463. this.onCollisionPositionChangeObservable.clear();
  14464. this._isDisposed = true;
  14465. _super.prototype.dispose.call(this);
  14466. };
  14467. /**
  14468. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14469. * This Vector3 is expressed in the World space.
  14470. */
  14471. AbstractMesh.prototype.getDirection = function (localAxis) {
  14472. var result = BABYLON.Vector3.Zero();
  14473. this.getDirectionToRef(localAxis, result);
  14474. return result;
  14475. };
  14476. /**
  14477. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14478. * localAxis is expressed in the mesh local space.
  14479. * result is computed in the Wordl space from the mesh World matrix.
  14480. * Returns the AbstractMesh.
  14481. */
  14482. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14483. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14484. return this;
  14485. };
  14486. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14487. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14488. if (this.getScene().getRenderId() == 0) {
  14489. this.computeWorldMatrix(true);
  14490. }
  14491. var wm = this.getWorldMatrix();
  14492. if (space == BABYLON.Space.WORLD) {
  14493. var tmat = BABYLON.Tmp.Matrix[0];
  14494. wm.invertToRef(tmat);
  14495. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14496. }
  14497. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14498. this._pivotMatrix.m[12] = -point.x;
  14499. this._pivotMatrix.m[13] = -point.y;
  14500. this._pivotMatrix.m[14] = -point.z;
  14501. this._cache.pivotMatrixUpdated = true;
  14502. return this;
  14503. };
  14504. /**
  14505. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14506. */
  14507. AbstractMesh.prototype.getPivotPoint = function () {
  14508. var point = BABYLON.Vector3.Zero();
  14509. this.getPivotPointToRef(point);
  14510. return point;
  14511. };
  14512. /**
  14513. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14514. * Returns the AbstractMesh.
  14515. */
  14516. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14517. result.x = -this._pivotMatrix.m[12];
  14518. result.y = -this._pivotMatrix.m[13];
  14519. result.z = -this._pivotMatrix.m[14];
  14520. return this;
  14521. };
  14522. /**
  14523. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14524. */
  14525. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14526. var point = BABYLON.Vector3.Zero();
  14527. this.getAbsolutePivotPointToRef(point);
  14528. return point;
  14529. };
  14530. /**
  14531. * Defines the passed mesh as the parent of the current mesh.
  14532. * Returns the AbstractMesh.
  14533. */
  14534. AbstractMesh.prototype.setParent = function (mesh) {
  14535. var parent = mesh;
  14536. if (mesh == null) {
  14537. var rotation = BABYLON.Tmp.Quaternion[0];
  14538. var position = BABYLON.Tmp.Vector3[0];
  14539. var scale = BABYLON.Tmp.Vector3[1];
  14540. this.getWorldMatrix().decompose(scale, rotation, position);
  14541. if (this.rotationQuaternion) {
  14542. this.rotationQuaternion.copyFrom(rotation);
  14543. }
  14544. else {
  14545. rotation.toEulerAnglesToRef(this.rotation);
  14546. }
  14547. this.position.x = position.x;
  14548. this.position.y = position.y;
  14549. this.position.z = position.z;
  14550. }
  14551. else {
  14552. var position = BABYLON.Tmp.Vector3[0];
  14553. var m1 = BABYLON.Tmp.Matrix[0];
  14554. parent.getWorldMatrix().invertToRef(m1);
  14555. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14556. this.position.copyFrom(position);
  14557. }
  14558. this.parent = parent;
  14559. return this;
  14560. };
  14561. /**
  14562. * Adds the passed mesh as a child to the current mesh.
  14563. * Returns the AbstractMesh.
  14564. */
  14565. AbstractMesh.prototype.addChild = function (mesh) {
  14566. mesh.setParent(this);
  14567. return this;
  14568. };
  14569. /**
  14570. * Removes the passed mesh from the current mesh children list.
  14571. * Returns the AbstractMesh.
  14572. */
  14573. AbstractMesh.prototype.removeChild = function (mesh) {
  14574. mesh.setParent(null);
  14575. return this;
  14576. };
  14577. /**
  14578. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14579. * Returns the AbstractMesh.
  14580. */
  14581. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14582. result.x = this._pivotMatrix.m[12];
  14583. result.y = this._pivotMatrix.m[13];
  14584. result.z = this._pivotMatrix.m[14];
  14585. this.getPivotPointToRef(result);
  14586. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14587. return this;
  14588. };
  14589. // Facet data
  14590. /**
  14591. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14592. * Returns the AbstractMesh.
  14593. */
  14594. AbstractMesh.prototype._initFacetData = function () {
  14595. if (!this._facetNormals) {
  14596. this._facetNormals = new Array();
  14597. }
  14598. if (!this._facetPositions) {
  14599. this._facetPositions = new Array();
  14600. }
  14601. if (!this._facetPartitioning) {
  14602. this._facetPartitioning = new Array();
  14603. }
  14604. this._facetNb = this.getIndices().length / 3;
  14605. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14606. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14607. for (var f = 0; f < this._facetNb; f++) {
  14608. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14609. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14610. }
  14611. this._facetDataEnabled = true;
  14612. return this;
  14613. };
  14614. /**
  14615. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14616. * This method can be called within the render loop.
  14617. * 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.
  14618. * Returns the AbstractMesh.
  14619. */
  14620. AbstractMesh.prototype.updateFacetData = function () {
  14621. if (!this._facetDataEnabled) {
  14622. this._initFacetData();
  14623. }
  14624. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14625. var indices = this.getIndices();
  14626. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14627. var bInfo = this.getBoundingInfo();
  14628. if (!bInfo) {
  14629. return this;
  14630. }
  14631. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14632. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14633. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14634. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14635. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14636. this._subDiv.max = this._partitioningSubdivisions;
  14637. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14638. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14639. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14640. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14641. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14642. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14643. // set the parameters for ComputeNormals()
  14644. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14645. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14646. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14647. this._facetParameters.bInfo = bInfo;
  14648. this._facetParameters.bbSize = this._bbSize;
  14649. this._facetParameters.subDiv = this._subDiv;
  14650. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14651. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14652. return this;
  14653. };
  14654. /**
  14655. * Returns the facetLocalNormals array.
  14656. * The normals are expressed in the mesh local space.
  14657. */
  14658. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14659. if (!this._facetNormals) {
  14660. this.updateFacetData();
  14661. }
  14662. return this._facetNormals;
  14663. };
  14664. /**
  14665. * Returns the facetLocalPositions array.
  14666. * The facet positions are expressed in the mesh local space.
  14667. */
  14668. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14669. if (!this._facetPositions) {
  14670. this.updateFacetData();
  14671. }
  14672. return this._facetPositions;
  14673. };
  14674. /**
  14675. * Returns the facetLocalPartioning array.
  14676. */
  14677. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14678. if (!this._facetPartitioning) {
  14679. this.updateFacetData();
  14680. }
  14681. return this._facetPartitioning;
  14682. };
  14683. /**
  14684. * Returns the i-th facet position in the world system.
  14685. * This method allocates a new Vector3 per call.
  14686. */
  14687. AbstractMesh.prototype.getFacetPosition = function (i) {
  14688. var pos = BABYLON.Vector3.Zero();
  14689. this.getFacetPositionToRef(i, pos);
  14690. return pos;
  14691. };
  14692. /**
  14693. * Sets the reference Vector3 with the i-th facet position in the world system.
  14694. * Returns the AbstractMesh.
  14695. */
  14696. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14697. var localPos = (this.getFacetLocalPositions())[i];
  14698. var world = this.getWorldMatrix();
  14699. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14700. return this;
  14701. };
  14702. /**
  14703. * Returns the i-th facet normal in the world system.
  14704. * This method allocates a new Vector3 per call.
  14705. */
  14706. AbstractMesh.prototype.getFacetNormal = function (i) {
  14707. var norm = BABYLON.Vector3.Zero();
  14708. this.getFacetNormalToRef(i, norm);
  14709. return norm;
  14710. };
  14711. /**
  14712. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14713. * Returns the AbstractMesh.
  14714. */
  14715. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14716. var localNorm = (this.getFacetLocalNormals())[i];
  14717. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14718. return this;
  14719. };
  14720. /**
  14721. * 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).
  14722. */
  14723. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14724. var bInfo = this.getBoundingInfo();
  14725. if (!bInfo) {
  14726. return null;
  14727. }
  14728. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14729. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14730. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14731. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14732. return null;
  14733. }
  14734. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14735. };
  14736. /**
  14737. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14738. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14739. * 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.
  14740. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14741. * 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.
  14742. */
  14743. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14744. if (checkFace === void 0) { checkFace = false; }
  14745. if (facing === void 0) { facing = true; }
  14746. var world = this.getWorldMatrix();
  14747. var invMat = BABYLON.Tmp.Matrix[5];
  14748. world.invertToRef(invMat);
  14749. var invVect = BABYLON.Tmp.Vector3[8];
  14750. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14751. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14752. if (projected) {
  14753. // tranform the local computed projected vector to world coordinates
  14754. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14755. }
  14756. return closest;
  14757. };
  14758. /**
  14759. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14760. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14761. * 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.
  14762. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14763. * 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.
  14764. */
  14765. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14766. if (checkFace === void 0) { checkFace = false; }
  14767. if (facing === void 0) { facing = true; }
  14768. var closest = null;
  14769. var tmpx = 0.0;
  14770. var tmpy = 0.0;
  14771. var tmpz = 0.0;
  14772. var d = 0.0; // tmp dot facet normal * facet position
  14773. var t0 = 0.0;
  14774. var projx = 0.0;
  14775. var projy = 0.0;
  14776. var projz = 0.0;
  14777. // Get all the facets in the same partitioning block than (x, y, z)
  14778. var facetPositions = this.getFacetLocalPositions();
  14779. var facetNormals = this.getFacetLocalNormals();
  14780. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14781. if (!facetsInBlock) {
  14782. return null;
  14783. }
  14784. // Get the closest facet to (x, y, z)
  14785. var shortest = Number.MAX_VALUE; // init distance vars
  14786. var tmpDistance = shortest;
  14787. var fib; // current facet in the block
  14788. var norm; // current facet normal
  14789. var p0; // current facet barycenter position
  14790. // loop on all the facets in the current partitioning block
  14791. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14792. fib = facetsInBlock[idx];
  14793. norm = facetNormals[fib];
  14794. p0 = facetPositions[fib];
  14795. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14796. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14797. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14798. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14799. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14800. projx = x + norm.x * t0;
  14801. projy = y + norm.y * t0;
  14802. projz = z + norm.z * t0;
  14803. tmpx = projx - x;
  14804. tmpy = projy - y;
  14805. tmpz = projz - z;
  14806. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14807. if (tmpDistance < shortest) {
  14808. shortest = tmpDistance;
  14809. closest = fib;
  14810. if (projected) {
  14811. projected.x = projx;
  14812. projected.y = projy;
  14813. projected.z = projz;
  14814. }
  14815. }
  14816. }
  14817. }
  14818. return closest;
  14819. };
  14820. /**
  14821. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14822. */
  14823. AbstractMesh.prototype.getFacetDataParameters = function () {
  14824. return this._facetParameters;
  14825. };
  14826. /**
  14827. * Disables the feature FacetData and frees the related memory.
  14828. * Returns the AbstractMesh.
  14829. */
  14830. AbstractMesh.prototype.disableFacetData = function () {
  14831. if (this._facetDataEnabled) {
  14832. this._facetDataEnabled = false;
  14833. this._facetPositions = new Array();
  14834. ;
  14835. this._facetNormals = new Array();
  14836. ;
  14837. this._facetPartitioning = new Array();
  14838. ;
  14839. this._facetParameters = null;
  14840. }
  14841. return this;
  14842. };
  14843. /**
  14844. * Creates new normals data for the mesh.
  14845. * @param updatable.
  14846. */
  14847. AbstractMesh.prototype.createNormals = function (updatable) {
  14848. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14849. var indices = this.getIndices();
  14850. var normals;
  14851. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14852. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14853. }
  14854. else {
  14855. normals = [];
  14856. }
  14857. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14858. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14859. };
  14860. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14861. var engine = this.getEngine();
  14862. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14863. this._isOccluded = false;
  14864. return;
  14865. }
  14866. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  14867. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14868. if (isOcclusionQueryAvailable) {
  14869. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14870. this._isOcclusionQueryInProgress = false;
  14871. this._occlusionInternalRetryCounter = 0;
  14872. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14873. }
  14874. else {
  14875. this._occlusionInternalRetryCounter++;
  14876. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14877. this._isOcclusionQueryInProgress = false;
  14878. this._occlusionInternalRetryCounter = 0;
  14879. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14880. // if strict continue the last state of the object.
  14881. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14882. }
  14883. else {
  14884. return;
  14885. }
  14886. }
  14887. }
  14888. var scene = this.getScene();
  14889. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14890. if (!this._occlusionQuery) {
  14891. this._occlusionQuery = engine.createQuery();
  14892. }
  14893. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14894. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14895. engine.endQuery(this.occlusionQueryAlgorithmType);
  14896. this._isOcclusionQueryInProgress = true;
  14897. };
  14898. // Statics
  14899. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14900. AbstractMesh._BILLBOARDMODE_X = 1;
  14901. AbstractMesh._BILLBOARDMODE_Y = 2;
  14902. AbstractMesh._BILLBOARDMODE_Z = 4;
  14903. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14904. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14905. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14906. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14907. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14908. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14909. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14910. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14911. return AbstractMesh;
  14912. }(BABYLON.Node));
  14913. BABYLON.AbstractMesh = AbstractMesh;
  14914. })(BABYLON || (BABYLON = {}));
  14915. //# sourceMappingURL=babylon.abstractMesh.js.map
  14916. var BABYLON;
  14917. (function (BABYLON) {
  14918. var Light = /** @class */ (function (_super) {
  14919. __extends(Light, _super);
  14920. /**
  14921. * Creates a Light object in the scene.
  14922. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14923. */
  14924. function Light(name, scene) {
  14925. var _this = _super.call(this, name, scene) || this;
  14926. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14927. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14928. _this.intensity = 1.0;
  14929. _this.range = Number.MAX_VALUE;
  14930. /**
  14931. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14932. * of light.
  14933. */
  14934. _this._photometricScale = 1.0;
  14935. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14936. _this._radius = 0.00001;
  14937. _this.renderPriority = 0;
  14938. /**
  14939. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14940. * the current shadow generator.
  14941. */
  14942. _this.shadowEnabled = true;
  14943. _this._excludeWithLayerMask = 0;
  14944. _this._includeOnlyWithLayerMask = 0;
  14945. _this._lightmapMode = 0;
  14946. _this._excludedMeshesIds = new Array();
  14947. _this._includedOnlyMeshesIds = new Array();
  14948. _this.getScene().addLight(_this);
  14949. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14950. _this._buildUniformLayout();
  14951. _this.includedOnlyMeshes = new Array();
  14952. _this.excludedMeshes = new Array();
  14953. _this._resyncMeshes();
  14954. return _this;
  14955. }
  14956. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14957. /**
  14958. * If every light affecting the material is in this lightmapMode,
  14959. * material.lightmapTexture adds or multiplies
  14960. * (depends on material.useLightmapAsShadowmap)
  14961. * after every other light calculations.
  14962. */
  14963. get: function () {
  14964. return Light._LIGHTMAP_DEFAULT;
  14965. },
  14966. enumerable: true,
  14967. configurable: true
  14968. });
  14969. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14970. /**
  14971. * material.lightmapTexture as only diffuse lighting from this light
  14972. * adds pnly specular lighting from this light
  14973. * adds dynamic shadows
  14974. */
  14975. get: function () {
  14976. return Light._LIGHTMAP_SPECULAR;
  14977. },
  14978. enumerable: true,
  14979. configurable: true
  14980. });
  14981. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14982. /**
  14983. * material.lightmapTexture as only lighting
  14984. * no light calculation from this light
  14985. * only adds dynamic shadows from this light
  14986. */
  14987. get: function () {
  14988. return Light._LIGHTMAP_SHADOWSONLY;
  14989. },
  14990. enumerable: true,
  14991. configurable: true
  14992. });
  14993. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14994. /**
  14995. * Each light type uses the default quantity according to its type:
  14996. * point/spot lights use luminous intensity
  14997. * directional lights use illuminance
  14998. */
  14999. get: function () {
  15000. return Light._INTENSITYMODE_AUTOMATIC;
  15001. },
  15002. enumerable: true,
  15003. configurable: true
  15004. });
  15005. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15006. /**
  15007. * lumen (lm)
  15008. */
  15009. get: function () {
  15010. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15011. },
  15012. enumerable: true,
  15013. configurable: true
  15014. });
  15015. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15016. /**
  15017. * candela (lm/sr)
  15018. */
  15019. get: function () {
  15020. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15021. },
  15022. enumerable: true,
  15023. configurable: true
  15024. });
  15025. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15026. /**
  15027. * lux (lm/m^2)
  15028. */
  15029. get: function () {
  15030. return Light._INTENSITYMODE_ILLUMINANCE;
  15031. },
  15032. enumerable: true,
  15033. configurable: true
  15034. });
  15035. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15036. /**
  15037. * nit (cd/m^2)
  15038. */
  15039. get: function () {
  15040. return Light._INTENSITYMODE_LUMINANCE;
  15041. },
  15042. enumerable: true,
  15043. configurable: true
  15044. });
  15045. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15046. /**
  15047. * Light type const id of the point light.
  15048. */
  15049. get: function () {
  15050. return Light._LIGHTTYPEID_POINTLIGHT;
  15051. },
  15052. enumerable: true,
  15053. configurable: true
  15054. });
  15055. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15056. /**
  15057. * Light type const id of the directional light.
  15058. */
  15059. get: function () {
  15060. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15061. },
  15062. enumerable: true,
  15063. configurable: true
  15064. });
  15065. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15066. /**
  15067. * Light type const id of the spot light.
  15068. */
  15069. get: function () {
  15070. return Light._LIGHTTYPEID_SPOTLIGHT;
  15071. },
  15072. enumerable: true,
  15073. configurable: true
  15074. });
  15075. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15076. /**
  15077. * Light type const id of the hemispheric light.
  15078. */
  15079. get: function () {
  15080. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15081. },
  15082. enumerable: true,
  15083. configurable: true
  15084. });
  15085. Object.defineProperty(Light.prototype, "intensityMode", {
  15086. /**
  15087. * Gets the photometric scale used to interpret the intensity.
  15088. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15089. */
  15090. get: function () {
  15091. return this._intensityMode;
  15092. },
  15093. /**
  15094. * Sets the photometric scale used to interpret the intensity.
  15095. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15096. */
  15097. set: function (value) {
  15098. this._intensityMode = value;
  15099. this._computePhotometricScale();
  15100. },
  15101. enumerable: true,
  15102. configurable: true
  15103. });
  15104. ;
  15105. ;
  15106. Object.defineProperty(Light.prototype, "radius", {
  15107. /**
  15108. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15109. */
  15110. get: function () {
  15111. return this._radius;
  15112. },
  15113. /**
  15114. * sets the light radius used by PBR Materials to simulate soft area lights.
  15115. */
  15116. set: function (value) {
  15117. this._radius = value;
  15118. this._computePhotometricScale();
  15119. },
  15120. enumerable: true,
  15121. configurable: true
  15122. });
  15123. ;
  15124. ;
  15125. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15126. get: function () {
  15127. return this._includedOnlyMeshes;
  15128. },
  15129. set: function (value) {
  15130. this._includedOnlyMeshes = value;
  15131. this._hookArrayForIncludedOnly(value);
  15132. },
  15133. enumerable: true,
  15134. configurable: true
  15135. });
  15136. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15137. get: function () {
  15138. return this._excludedMeshes;
  15139. },
  15140. set: function (value) {
  15141. this._excludedMeshes = value;
  15142. this._hookArrayForExcluded(value);
  15143. },
  15144. enumerable: true,
  15145. configurable: true
  15146. });
  15147. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15148. get: function () {
  15149. return this._excludeWithLayerMask;
  15150. },
  15151. set: function (value) {
  15152. this._excludeWithLayerMask = value;
  15153. this._resyncMeshes();
  15154. },
  15155. enumerable: true,
  15156. configurable: true
  15157. });
  15158. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15159. get: function () {
  15160. return this._includeOnlyWithLayerMask;
  15161. },
  15162. set: function (value) {
  15163. this._includeOnlyWithLayerMask = value;
  15164. this._resyncMeshes();
  15165. },
  15166. enumerable: true,
  15167. configurable: true
  15168. });
  15169. Object.defineProperty(Light.prototype, "lightmapMode", {
  15170. get: function () {
  15171. return this._lightmapMode;
  15172. },
  15173. set: function (value) {
  15174. if (this._lightmapMode === value) {
  15175. return;
  15176. }
  15177. this._lightmapMode = value;
  15178. this._markMeshesAsLightDirty();
  15179. },
  15180. enumerable: true,
  15181. configurable: true
  15182. });
  15183. Light.prototype._buildUniformLayout = function () {
  15184. // Overridden
  15185. };
  15186. /**
  15187. * Returns the string "Light".
  15188. */
  15189. Light.prototype.getClassName = function () {
  15190. return "Light";
  15191. };
  15192. /**
  15193. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15194. */
  15195. Light.prototype.toString = function (fullDetails) {
  15196. var ret = "Name: " + this.name;
  15197. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15198. if (this.animations) {
  15199. for (var i = 0; i < this.animations.length; i++) {
  15200. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15201. }
  15202. }
  15203. if (fullDetails) {
  15204. }
  15205. return ret;
  15206. };
  15207. /**
  15208. * Set the enabled state of this node.
  15209. * @param {boolean} value - the new enabled state
  15210. * @see isEnabled
  15211. */
  15212. Light.prototype.setEnabled = function (value) {
  15213. _super.prototype.setEnabled.call(this, value);
  15214. this._resyncMeshes();
  15215. };
  15216. /**
  15217. * Returns the Light associated shadow generator.
  15218. */
  15219. Light.prototype.getShadowGenerator = function () {
  15220. return this._shadowGenerator;
  15221. };
  15222. /**
  15223. * Returns a Vector3, the absolute light position in the World.
  15224. */
  15225. Light.prototype.getAbsolutePosition = function () {
  15226. return BABYLON.Vector3.Zero();
  15227. };
  15228. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15229. };
  15230. Light.prototype._getWorldMatrix = function () {
  15231. return BABYLON.Matrix.Identity();
  15232. };
  15233. /**
  15234. * Boolean : True if the light will affect the passed mesh.
  15235. */
  15236. Light.prototype.canAffectMesh = function (mesh) {
  15237. if (!mesh) {
  15238. return true;
  15239. }
  15240. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15241. return false;
  15242. }
  15243. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15244. return false;
  15245. }
  15246. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15247. return false;
  15248. }
  15249. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15250. return false;
  15251. }
  15252. return true;
  15253. };
  15254. /**
  15255. * Returns the light World matrix.
  15256. */
  15257. Light.prototype.getWorldMatrix = function () {
  15258. this._currentRenderId = this.getScene().getRenderId();
  15259. var worldMatrix = this._getWorldMatrix();
  15260. if (this.parent && this.parent.getWorldMatrix) {
  15261. if (!this._parentedWorldMatrix) {
  15262. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15263. }
  15264. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15265. this._markSyncedWithParent();
  15266. return this._parentedWorldMatrix;
  15267. }
  15268. return worldMatrix;
  15269. };
  15270. /**
  15271. * Sort function to order lights for rendering.
  15272. * @param a First Light object to compare to second.
  15273. * @param b Second Light object to compare first.
  15274. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15275. */
  15276. Light.compareLightsPriority = function (a, b) {
  15277. //shadow-casting lights have priority over non-shadow-casting lights
  15278. //the renderPrioirty is a secondary sort criterion
  15279. if (a.shadowEnabled !== b.shadowEnabled) {
  15280. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15281. }
  15282. return b.renderPriority - a.renderPriority;
  15283. };
  15284. /**
  15285. * Disposes the light.
  15286. */
  15287. Light.prototype.dispose = function () {
  15288. if (this._shadowGenerator) {
  15289. this._shadowGenerator.dispose();
  15290. this._shadowGenerator = null;
  15291. }
  15292. // Animations
  15293. this.getScene().stopAnimation(this);
  15294. // Remove from meshes
  15295. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15296. var mesh = _a[_i];
  15297. mesh._removeLightSource(this);
  15298. }
  15299. this._uniformBuffer.dispose();
  15300. // Remove from scene
  15301. this.getScene().removeLight(this);
  15302. _super.prototype.dispose.call(this);
  15303. };
  15304. /**
  15305. * Returns the light type ID (integer).
  15306. */
  15307. Light.prototype.getTypeID = function () {
  15308. return 0;
  15309. };
  15310. /**
  15311. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15312. */
  15313. Light.prototype.getScaledIntensity = function () {
  15314. return this._photometricScale * this.intensity;
  15315. };
  15316. /**
  15317. * Returns a new Light object, named "name", from the current one.
  15318. */
  15319. Light.prototype.clone = function (name) {
  15320. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15321. if (!constructor) {
  15322. return null;
  15323. }
  15324. return BABYLON.SerializationHelper.Clone(constructor, this);
  15325. };
  15326. /**
  15327. * Serializes the current light into a Serialization object.
  15328. * Returns the serialized object.
  15329. */
  15330. Light.prototype.serialize = function () {
  15331. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15332. // Type
  15333. serializationObject.type = this.getTypeID();
  15334. // Parent
  15335. if (this.parent) {
  15336. serializationObject.parentId = this.parent.id;
  15337. }
  15338. // Inclusion / exclusions
  15339. if (this.excludedMeshes.length > 0) {
  15340. serializationObject.excludedMeshesIds = [];
  15341. this.excludedMeshes.forEach(function (mesh) {
  15342. serializationObject.excludedMeshesIds.push(mesh.id);
  15343. });
  15344. }
  15345. if (this.includedOnlyMeshes.length > 0) {
  15346. serializationObject.includedOnlyMeshesIds = [];
  15347. this.includedOnlyMeshes.forEach(function (mesh) {
  15348. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15349. });
  15350. }
  15351. // Animations
  15352. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15353. serializationObject.ranges = this.serializeAnimationRanges();
  15354. return serializationObject;
  15355. };
  15356. /**
  15357. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15358. * This new light is named "name" and added to the passed scene.
  15359. */
  15360. Light.GetConstructorFromName = function (type, name, scene) {
  15361. switch (type) {
  15362. case 0:
  15363. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15364. case 1:
  15365. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15366. case 2:
  15367. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15368. case 3:
  15369. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15370. }
  15371. return null;
  15372. };
  15373. /**
  15374. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15375. */
  15376. Light.Parse = function (parsedLight, scene) {
  15377. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15378. if (!constructor) {
  15379. return null;
  15380. }
  15381. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15382. // Inclusion / exclusions
  15383. if (parsedLight.excludedMeshesIds) {
  15384. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15385. }
  15386. if (parsedLight.includedOnlyMeshesIds) {
  15387. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15388. }
  15389. // Parent
  15390. if (parsedLight.parentId) {
  15391. light._waitingParentId = parsedLight.parentId;
  15392. }
  15393. // Animations
  15394. if (parsedLight.animations) {
  15395. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15396. var parsedAnimation = parsedLight.animations[animationIndex];
  15397. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15398. }
  15399. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15400. }
  15401. if (parsedLight.autoAnimate) {
  15402. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15403. }
  15404. return light;
  15405. };
  15406. Light.prototype._hookArrayForExcluded = function (array) {
  15407. var _this = this;
  15408. var oldPush = array.push;
  15409. array.push = function () {
  15410. var items = [];
  15411. for (var _i = 0; _i < arguments.length; _i++) {
  15412. items[_i] = arguments[_i];
  15413. }
  15414. var result = oldPush.apply(array, items);
  15415. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15416. var item = items_1[_a];
  15417. item._resyncLighSource(_this);
  15418. }
  15419. return result;
  15420. };
  15421. var oldSplice = array.splice;
  15422. array.splice = function (index, deleteCount) {
  15423. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15424. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15425. var item = deleted_1[_i];
  15426. item._resyncLighSource(_this);
  15427. }
  15428. return deleted;
  15429. };
  15430. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15431. var item = array_1[_i];
  15432. item._resyncLighSource(this);
  15433. }
  15434. };
  15435. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15436. var _this = this;
  15437. var oldPush = array.push;
  15438. array.push = function () {
  15439. var items = [];
  15440. for (var _i = 0; _i < arguments.length; _i++) {
  15441. items[_i] = arguments[_i];
  15442. }
  15443. var result = oldPush.apply(array, items);
  15444. _this._resyncMeshes();
  15445. return result;
  15446. };
  15447. var oldSplice = array.splice;
  15448. array.splice = function (index, deleteCount) {
  15449. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15450. _this._resyncMeshes();
  15451. return deleted;
  15452. };
  15453. this._resyncMeshes();
  15454. };
  15455. Light.prototype._resyncMeshes = function () {
  15456. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15457. var mesh = _a[_i];
  15458. mesh._resyncLighSource(this);
  15459. }
  15460. };
  15461. Light.prototype._markMeshesAsLightDirty = function () {
  15462. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15463. var mesh = _a[_i];
  15464. if (mesh._lightSources.indexOf(this) !== -1) {
  15465. mesh._markSubMeshesAsLightDirty();
  15466. }
  15467. }
  15468. };
  15469. /**
  15470. * Recomputes the cached photometric scale if needed.
  15471. */
  15472. Light.prototype._computePhotometricScale = function () {
  15473. this._photometricScale = this._getPhotometricScale();
  15474. this.getScene().resetCachedMaterial();
  15475. };
  15476. /**
  15477. * Returns the Photometric Scale according to the light type and intensity mode.
  15478. */
  15479. Light.prototype._getPhotometricScale = function () {
  15480. var photometricScale = 0.0;
  15481. var lightTypeID = this.getTypeID();
  15482. //get photometric mode
  15483. var photometricMode = this.intensityMode;
  15484. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15485. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15486. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15487. }
  15488. else {
  15489. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15490. }
  15491. }
  15492. //compute photometric scale
  15493. switch (lightTypeID) {
  15494. case Light.LIGHTTYPEID_POINTLIGHT:
  15495. case Light.LIGHTTYPEID_SPOTLIGHT:
  15496. switch (photometricMode) {
  15497. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15498. photometricScale = 1.0 / (4.0 * Math.PI);
  15499. break;
  15500. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15501. photometricScale = 1.0;
  15502. break;
  15503. case Light.INTENSITYMODE_LUMINANCE:
  15504. photometricScale = this.radius * this.radius;
  15505. break;
  15506. }
  15507. break;
  15508. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15509. switch (photometricMode) {
  15510. case Light.INTENSITYMODE_ILLUMINANCE:
  15511. photometricScale = 1.0;
  15512. break;
  15513. case Light.INTENSITYMODE_LUMINANCE:
  15514. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15515. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15516. var apexAngleRadians = this.radius;
  15517. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15518. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15519. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15520. photometricScale = solidAngle;
  15521. break;
  15522. }
  15523. break;
  15524. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15525. // No fall off in hemisperic light.
  15526. photometricScale = 1.0;
  15527. break;
  15528. }
  15529. return photometricScale;
  15530. };
  15531. Light.prototype._reorderLightsInScene = function () {
  15532. var scene = this.getScene();
  15533. if (this._renderPriority != 0) {
  15534. scene.requireLightSorting = true;
  15535. }
  15536. this.getScene().sortLightsByPriority();
  15537. };
  15538. //lightmapMode Consts
  15539. Light._LIGHTMAP_DEFAULT = 0;
  15540. Light._LIGHTMAP_SPECULAR = 1;
  15541. Light._LIGHTMAP_SHADOWSONLY = 2;
  15542. // Intensity Mode Consts
  15543. Light._INTENSITYMODE_AUTOMATIC = 0;
  15544. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15545. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15546. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15547. Light._INTENSITYMODE_LUMINANCE = 4;
  15548. // Light types ids const.
  15549. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15550. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15551. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15552. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15553. __decorate([
  15554. BABYLON.serializeAsColor3()
  15555. ], Light.prototype, "diffuse", void 0);
  15556. __decorate([
  15557. BABYLON.serializeAsColor3()
  15558. ], Light.prototype, "specular", void 0);
  15559. __decorate([
  15560. BABYLON.serialize()
  15561. ], Light.prototype, "intensity", void 0);
  15562. __decorate([
  15563. BABYLON.serialize()
  15564. ], Light.prototype, "range", void 0);
  15565. __decorate([
  15566. BABYLON.serialize()
  15567. ], Light.prototype, "intensityMode", null);
  15568. __decorate([
  15569. BABYLON.serialize()
  15570. ], Light.prototype, "radius", null);
  15571. __decorate([
  15572. BABYLON.serialize()
  15573. ], Light.prototype, "_renderPriority", void 0);
  15574. __decorate([
  15575. BABYLON.expandToProperty("_reorderLightsInScene")
  15576. ], Light.prototype, "renderPriority", void 0);
  15577. __decorate([
  15578. BABYLON.serialize()
  15579. ], Light.prototype, "shadowEnabled", void 0);
  15580. __decorate([
  15581. BABYLON.serialize("excludeWithLayerMask")
  15582. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15583. __decorate([
  15584. BABYLON.serialize("includeOnlyWithLayerMask")
  15585. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15586. __decorate([
  15587. BABYLON.serialize("lightmapMode")
  15588. ], Light.prototype, "_lightmapMode", void 0);
  15589. return Light;
  15590. }(BABYLON.Node));
  15591. BABYLON.Light = Light;
  15592. })(BABYLON || (BABYLON = {}));
  15593. //# sourceMappingURL=babylon.light.js.map
  15594. var BABYLON;
  15595. (function (BABYLON) {
  15596. var Camera = /** @class */ (function (_super) {
  15597. __extends(Camera, _super);
  15598. function Camera(name, position, scene) {
  15599. var _this = _super.call(this, name, scene) || this;
  15600. _this.upVector = BABYLON.Vector3.Up();
  15601. _this.orthoLeft = null;
  15602. _this.orthoRight = null;
  15603. _this.orthoBottom = null;
  15604. _this.orthoTop = null;
  15605. _this.fov = 0.8;
  15606. _this.minZ = 1;
  15607. _this.maxZ = 10000.0;
  15608. _this.inertia = 0.9;
  15609. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15610. _this.isIntermediate = false;
  15611. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15612. _this.layerMask = 0x0FFFFFFF;
  15613. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15614. // Camera rig members
  15615. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15616. _this._rigCameras = new Array();
  15617. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15618. _this._skipRendering = false;
  15619. _this.customRenderTargets = new Array();
  15620. // Observables
  15621. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15622. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15623. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15624. _this.onRestoreStateObservable = new BABYLON.Observable();
  15625. // Cache
  15626. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15627. _this._projectionMatrix = new BABYLON.Matrix();
  15628. _this._doNotComputeProjectionMatrix = false;
  15629. _this._postProcesses = new Array();
  15630. _this._transformMatrix = BABYLON.Matrix.Zero();
  15631. _this._activeMeshes = new BABYLON.SmartArray(256);
  15632. _this._globalPosition = BABYLON.Vector3.Zero();
  15633. _this._refreshFrustumPlanes = true;
  15634. _this.getScene().addCamera(_this);
  15635. if (!_this.getScene().activeCamera) {
  15636. _this.getScene().activeCamera = _this;
  15637. }
  15638. _this.position = position;
  15639. return _this;
  15640. }
  15641. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15642. get: function () {
  15643. return Camera._PERSPECTIVE_CAMERA;
  15644. },
  15645. enumerable: true,
  15646. configurable: true
  15647. });
  15648. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15649. get: function () {
  15650. return Camera._ORTHOGRAPHIC_CAMERA;
  15651. },
  15652. enumerable: true,
  15653. configurable: true
  15654. });
  15655. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15656. get: function () {
  15657. return Camera._FOVMODE_VERTICAL_FIXED;
  15658. },
  15659. enumerable: true,
  15660. configurable: true
  15661. });
  15662. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15663. get: function () {
  15664. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15665. },
  15666. enumerable: true,
  15667. configurable: true
  15668. });
  15669. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15670. get: function () {
  15671. return Camera._RIG_MODE_NONE;
  15672. },
  15673. enumerable: true,
  15674. configurable: true
  15675. });
  15676. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15677. get: function () {
  15678. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15679. },
  15680. enumerable: true,
  15681. configurable: true
  15682. });
  15683. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15684. get: function () {
  15685. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15686. },
  15687. enumerable: true,
  15688. configurable: true
  15689. });
  15690. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15691. get: function () {
  15692. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15693. },
  15694. enumerable: true,
  15695. configurable: true
  15696. });
  15697. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15698. get: function () {
  15699. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15700. },
  15701. enumerable: true,
  15702. configurable: true
  15703. });
  15704. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15705. get: function () {
  15706. return Camera._RIG_MODE_VR;
  15707. },
  15708. enumerable: true,
  15709. configurable: true
  15710. });
  15711. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15712. get: function () {
  15713. return Camera._RIG_MODE_WEBVR;
  15714. },
  15715. enumerable: true,
  15716. configurable: true
  15717. });
  15718. /**
  15719. * Store current camera state (fov, position, etc..)
  15720. */
  15721. Camera.prototype.storeState = function () {
  15722. this._stateStored = true;
  15723. this._storedFov = this.fov;
  15724. return this;
  15725. };
  15726. /**
  15727. * Restores the camera state values if it has been stored. You must call storeState() first
  15728. */
  15729. Camera.prototype._restoreStateValues = function () {
  15730. if (!this._stateStored) {
  15731. return false;
  15732. }
  15733. this.fov = this._storedFov;
  15734. return true;
  15735. };
  15736. /**
  15737. * Restored camera state. You must call storeState() first
  15738. */
  15739. Camera.prototype.restoreState = function () {
  15740. if (this._restoreStateValues()) {
  15741. this.onRestoreStateObservable.notifyObservers(this);
  15742. return true;
  15743. }
  15744. return false;
  15745. };
  15746. Camera.prototype.getClassName = function () {
  15747. return "Camera";
  15748. };
  15749. /**
  15750. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15751. */
  15752. Camera.prototype.toString = function (fullDetails) {
  15753. var ret = "Name: " + this.name;
  15754. ret += ", type: " + this.getClassName();
  15755. if (this.animations) {
  15756. for (var i = 0; i < this.animations.length; i++) {
  15757. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15758. }
  15759. }
  15760. if (fullDetails) {
  15761. }
  15762. return ret;
  15763. };
  15764. Object.defineProperty(Camera.prototype, "globalPosition", {
  15765. get: function () {
  15766. return this._globalPosition;
  15767. },
  15768. enumerable: true,
  15769. configurable: true
  15770. });
  15771. Camera.prototype.getActiveMeshes = function () {
  15772. return this._activeMeshes;
  15773. };
  15774. Camera.prototype.isActiveMesh = function (mesh) {
  15775. return (this._activeMeshes.indexOf(mesh) !== -1);
  15776. };
  15777. //Cache
  15778. Camera.prototype._initCache = function () {
  15779. _super.prototype._initCache.call(this);
  15780. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15781. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15782. this._cache.mode = undefined;
  15783. this._cache.minZ = undefined;
  15784. this._cache.maxZ = undefined;
  15785. this._cache.fov = undefined;
  15786. this._cache.fovMode = undefined;
  15787. this._cache.aspectRatio = undefined;
  15788. this._cache.orthoLeft = undefined;
  15789. this._cache.orthoRight = undefined;
  15790. this._cache.orthoBottom = undefined;
  15791. this._cache.orthoTop = undefined;
  15792. this._cache.renderWidth = undefined;
  15793. this._cache.renderHeight = undefined;
  15794. };
  15795. Camera.prototype._updateCache = function (ignoreParentClass) {
  15796. if (!ignoreParentClass) {
  15797. _super.prototype._updateCache.call(this);
  15798. }
  15799. this._cache.position.copyFrom(this.position);
  15800. this._cache.upVector.copyFrom(this.upVector);
  15801. };
  15802. // Synchronized
  15803. Camera.prototype._isSynchronized = function () {
  15804. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15805. };
  15806. Camera.prototype._isSynchronizedViewMatrix = function () {
  15807. if (!_super.prototype._isSynchronized.call(this))
  15808. return false;
  15809. return this._cache.position.equals(this.position)
  15810. && this._cache.upVector.equals(this.upVector)
  15811. && this.isSynchronizedWithParent();
  15812. };
  15813. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15814. var check = this._cache.mode === this.mode
  15815. && this._cache.minZ === this.minZ
  15816. && this._cache.maxZ === this.maxZ;
  15817. if (!check) {
  15818. return false;
  15819. }
  15820. var engine = this.getEngine();
  15821. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15822. check = this._cache.fov === this.fov
  15823. && this._cache.fovMode === this.fovMode
  15824. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15825. }
  15826. else {
  15827. check = this._cache.orthoLeft === this.orthoLeft
  15828. && this._cache.orthoRight === this.orthoRight
  15829. && this._cache.orthoBottom === this.orthoBottom
  15830. && this._cache.orthoTop === this.orthoTop
  15831. && this._cache.renderWidth === engine.getRenderWidth()
  15832. && this._cache.renderHeight === engine.getRenderHeight();
  15833. }
  15834. return check;
  15835. };
  15836. // Controls
  15837. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15838. };
  15839. Camera.prototype.detachControl = function (element) {
  15840. };
  15841. Camera.prototype.update = function () {
  15842. this._checkInputs();
  15843. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15844. this._updateRigCameras();
  15845. }
  15846. };
  15847. Camera.prototype._checkInputs = function () {
  15848. this.onAfterCheckInputsObservable.notifyObservers(this);
  15849. };
  15850. Object.defineProperty(Camera.prototype, "rigCameras", {
  15851. get: function () {
  15852. return this._rigCameras;
  15853. },
  15854. enumerable: true,
  15855. configurable: true
  15856. });
  15857. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15858. get: function () {
  15859. return this._rigPostProcess;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15865. // invalidate framebuffer
  15866. if (this._postProcesses.length > 0) {
  15867. this._postProcesses[0].markTextureDirty();
  15868. }
  15869. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15870. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15871. var cam = this._rigCameras[i];
  15872. var rigPostProcess = cam._rigPostProcess;
  15873. // for VR rig, there does not have to be a post process
  15874. if (rigPostProcess) {
  15875. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15876. if (isPass) {
  15877. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15878. cam.isIntermediate = this._postProcesses.length === 0;
  15879. }
  15880. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15881. rigPostProcess.markTextureDirty();
  15882. }
  15883. else {
  15884. cam._postProcesses = this._postProcesses.slice(0);
  15885. }
  15886. }
  15887. };
  15888. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15889. if (insertAt === void 0) { insertAt = null; }
  15890. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15891. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15892. return 0;
  15893. }
  15894. if (insertAt == null || insertAt < 0) {
  15895. this._postProcesses.push(postProcess);
  15896. }
  15897. else {
  15898. this._postProcesses.splice(insertAt, 0, postProcess);
  15899. }
  15900. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15901. return this._postProcesses.indexOf(postProcess);
  15902. };
  15903. Camera.prototype.detachPostProcess = function (postProcess) {
  15904. var idx = this._postProcesses.indexOf(postProcess);
  15905. if (idx !== -1) {
  15906. this._postProcesses.splice(idx, 1);
  15907. }
  15908. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15909. };
  15910. Camera.prototype.getWorldMatrix = function () {
  15911. if (!this._worldMatrix) {
  15912. this._worldMatrix = BABYLON.Matrix.Identity();
  15913. }
  15914. var viewMatrix = this.getViewMatrix();
  15915. viewMatrix.invertToRef(this._worldMatrix);
  15916. return this._worldMatrix;
  15917. };
  15918. Camera.prototype._getViewMatrix = function () {
  15919. return BABYLON.Matrix.Identity();
  15920. };
  15921. Camera.prototype.getViewMatrix = function (force) {
  15922. if (!force && this._isSynchronizedViewMatrix()) {
  15923. return this._computedViewMatrix;
  15924. }
  15925. this.updateCache();
  15926. this._computedViewMatrix = this._getViewMatrix();
  15927. this._currentRenderId = this.getScene().getRenderId();
  15928. this._refreshFrustumPlanes = true;
  15929. if (!this.parent || !this.parent.getWorldMatrix) {
  15930. this._globalPosition.copyFrom(this.position);
  15931. }
  15932. else {
  15933. if (!this._worldMatrix) {
  15934. this._worldMatrix = BABYLON.Matrix.Identity();
  15935. }
  15936. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15937. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15938. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15939. this._computedViewMatrix.invert();
  15940. this._markSyncedWithParent();
  15941. }
  15942. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15943. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15944. }
  15945. this.onViewMatrixChangedObservable.notifyObservers(this);
  15946. return this._computedViewMatrix;
  15947. };
  15948. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15949. this._doNotComputeProjectionMatrix = true;
  15950. if (projection !== undefined) {
  15951. this._projectionMatrix = projection;
  15952. }
  15953. };
  15954. ;
  15955. Camera.prototype.unfreezeProjectionMatrix = function () {
  15956. this._doNotComputeProjectionMatrix = false;
  15957. };
  15958. ;
  15959. Camera.prototype.getProjectionMatrix = function (force) {
  15960. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15961. return this._projectionMatrix;
  15962. }
  15963. // Cache
  15964. this._cache.mode = this.mode;
  15965. this._cache.minZ = this.minZ;
  15966. this._cache.maxZ = this.maxZ;
  15967. // Matrix
  15968. this._refreshFrustumPlanes = true;
  15969. var engine = this.getEngine();
  15970. var scene = this.getScene();
  15971. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15972. this._cache.fov = this.fov;
  15973. this._cache.fovMode = this.fovMode;
  15974. this._cache.aspectRatio = engine.getAspectRatio(this);
  15975. if (this.minZ <= 0) {
  15976. this.minZ = 0.1;
  15977. }
  15978. if (scene.useRightHandedSystem) {
  15979. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15980. }
  15981. else {
  15982. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15983. }
  15984. }
  15985. else {
  15986. var halfWidth = engine.getRenderWidth() / 2.0;
  15987. var halfHeight = engine.getRenderHeight() / 2.0;
  15988. if (scene.useRightHandedSystem) {
  15989. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15990. }
  15991. else {
  15992. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15993. }
  15994. this._cache.orthoLeft = this.orthoLeft;
  15995. this._cache.orthoRight = this.orthoRight;
  15996. this._cache.orthoBottom = this.orthoBottom;
  15997. this._cache.orthoTop = this.orthoTop;
  15998. this._cache.renderWidth = engine.getRenderWidth();
  15999. this._cache.renderHeight = engine.getRenderHeight();
  16000. }
  16001. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16002. return this._projectionMatrix;
  16003. };
  16004. Camera.prototype.getTranformationMatrix = function () {
  16005. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16006. return this._transformMatrix;
  16007. };
  16008. Camera.prototype.updateFrustumPlanes = function () {
  16009. if (!this._refreshFrustumPlanes) {
  16010. return;
  16011. }
  16012. this.getTranformationMatrix();
  16013. if (!this._frustumPlanes) {
  16014. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16015. }
  16016. else {
  16017. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16018. }
  16019. this._refreshFrustumPlanes = false;
  16020. };
  16021. Camera.prototype.isInFrustum = function (target) {
  16022. this.updateFrustumPlanes();
  16023. return target.isInFrustum(this._frustumPlanes);
  16024. };
  16025. Camera.prototype.isCompletelyInFrustum = function (target) {
  16026. this.updateFrustumPlanes();
  16027. return target.isCompletelyInFrustum(this._frustumPlanes);
  16028. };
  16029. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16030. if (length === void 0) { length = 100; }
  16031. if (!transform) {
  16032. transform = this.getWorldMatrix();
  16033. }
  16034. if (!origin) {
  16035. origin = this.position;
  16036. }
  16037. var forward = new BABYLON.Vector3(0, 0, 1);
  16038. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16039. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16040. return new BABYLON.Ray(origin, direction, length);
  16041. };
  16042. Camera.prototype.dispose = function () {
  16043. // Observables
  16044. this.onViewMatrixChangedObservable.clear();
  16045. this.onProjectionMatrixChangedObservable.clear();
  16046. this.onAfterCheckInputsObservable.clear();
  16047. this.onRestoreStateObservable.clear();
  16048. // Inputs
  16049. if (this.inputs) {
  16050. this.inputs.clear();
  16051. }
  16052. // Animations
  16053. this.getScene().stopAnimation(this);
  16054. // Remove from scene
  16055. this.getScene().removeCamera(this);
  16056. while (this._rigCameras.length > 0) {
  16057. var camera = this._rigCameras.pop();
  16058. if (camera) {
  16059. camera.dispose();
  16060. }
  16061. }
  16062. // Postprocesses
  16063. if (this._rigPostProcess) {
  16064. this._rigPostProcess.dispose(this);
  16065. this._rigPostProcess = null;
  16066. this._postProcesses = [];
  16067. }
  16068. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16069. this._rigPostProcess = null;
  16070. this._postProcesses = [];
  16071. }
  16072. else {
  16073. var i = this._postProcesses.length;
  16074. while (--i >= 0) {
  16075. this._postProcesses[i].dispose(this);
  16076. }
  16077. }
  16078. // Render targets
  16079. var i = this.customRenderTargets.length;
  16080. while (--i >= 0) {
  16081. this.customRenderTargets[i].dispose();
  16082. }
  16083. this.customRenderTargets = [];
  16084. // Active Meshes
  16085. this._activeMeshes.dispose();
  16086. _super.prototype.dispose.call(this);
  16087. };
  16088. Object.defineProperty(Camera.prototype, "leftCamera", {
  16089. // ---- Camera rigs section ----
  16090. get: function () {
  16091. if (this._rigCameras.length < 1) {
  16092. return null;
  16093. }
  16094. return this._rigCameras[0];
  16095. },
  16096. enumerable: true,
  16097. configurable: true
  16098. });
  16099. Object.defineProperty(Camera.prototype, "rightCamera", {
  16100. get: function () {
  16101. if (this._rigCameras.length < 2) {
  16102. return null;
  16103. }
  16104. return this._rigCameras[1];
  16105. },
  16106. enumerable: true,
  16107. configurable: true
  16108. });
  16109. Camera.prototype.getLeftTarget = function () {
  16110. if (this._rigCameras.length < 1) {
  16111. return null;
  16112. }
  16113. return this._rigCameras[0].getTarget();
  16114. };
  16115. Camera.prototype.getRightTarget = function () {
  16116. if (this._rigCameras.length < 2) {
  16117. return null;
  16118. }
  16119. return this._rigCameras[1].getTarget();
  16120. };
  16121. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16122. if (this.cameraRigMode === mode) {
  16123. return;
  16124. }
  16125. while (this._rigCameras.length > 0) {
  16126. var camera = this._rigCameras.pop();
  16127. if (camera) {
  16128. camera.dispose();
  16129. }
  16130. }
  16131. this.cameraRigMode = mode;
  16132. this._cameraRigParams = {};
  16133. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16134. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16135. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16136. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16137. // create the rig cameras, unless none
  16138. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16139. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16140. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16141. if (leftCamera && rightCamera) {
  16142. this._rigCameras.push(leftCamera);
  16143. this._rigCameras.push(rightCamera);
  16144. }
  16145. }
  16146. switch (this.cameraRigMode) {
  16147. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16148. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16149. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16150. break;
  16151. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16152. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16153. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16154. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16155. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16156. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16157. break;
  16158. case Camera.RIG_MODE_VR:
  16159. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16160. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16161. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16162. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16163. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16164. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16165. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16166. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16167. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16168. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16169. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16170. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16171. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16172. if (metrics.compensateDistortion) {
  16173. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16174. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16175. }
  16176. break;
  16177. case Camera.RIG_MODE_WEBVR:
  16178. if (rigParams.vrDisplay) {
  16179. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16180. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16181. //Left eye
  16182. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16183. this._rigCameras[0].setCameraRigParameter("left", true);
  16184. //leaving this for future reference
  16185. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16186. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16187. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16188. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16189. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16190. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16191. this._rigCameras[0].parent = this;
  16192. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16193. //Right eye
  16194. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16195. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16196. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16197. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16198. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16199. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16200. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16201. this._rigCameras[1].parent = this;
  16202. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16203. if (Camera.UseAlternateWebVRRendering) {
  16204. this._rigCameras[1]._skipRendering = true;
  16205. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16206. }
  16207. }
  16208. break;
  16209. }
  16210. this._cascadePostProcessesToRigCams();
  16211. this.update();
  16212. };
  16213. Camera.prototype._getVRProjectionMatrix = function () {
  16214. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16215. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16216. return this._projectionMatrix;
  16217. };
  16218. Camera.prototype._updateCameraRotationMatrix = function () {
  16219. //Here for WebVR
  16220. };
  16221. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16222. //Here for WebVR
  16223. };
  16224. /**
  16225. * This function MUST be overwritten by the different WebVR cameras available.
  16226. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16227. */
  16228. Camera.prototype._getWebVRProjectionMatrix = function () {
  16229. return BABYLON.Matrix.Identity();
  16230. };
  16231. /**
  16232. * This function MUST be overwritten by the different WebVR cameras available.
  16233. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16234. */
  16235. Camera.prototype._getWebVRViewMatrix = function () {
  16236. return BABYLON.Matrix.Identity();
  16237. };
  16238. Camera.prototype.setCameraRigParameter = function (name, value) {
  16239. if (!this._cameraRigParams) {
  16240. this._cameraRigParams = {};
  16241. }
  16242. this._cameraRigParams[name] = value;
  16243. //provisionnally:
  16244. if (name === "interaxialDistance") {
  16245. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16246. }
  16247. };
  16248. /**
  16249. * needs to be overridden by children so sub has required properties to be copied
  16250. */
  16251. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16252. return null;
  16253. };
  16254. /**
  16255. * May need to be overridden by children
  16256. */
  16257. Camera.prototype._updateRigCameras = function () {
  16258. for (var i = 0; i < this._rigCameras.length; i++) {
  16259. this._rigCameras[i].minZ = this.minZ;
  16260. this._rigCameras[i].maxZ = this.maxZ;
  16261. this._rigCameras[i].fov = this.fov;
  16262. }
  16263. // only update viewport when ANAGLYPH
  16264. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16265. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16266. }
  16267. };
  16268. Camera.prototype._setupInputs = function () {
  16269. };
  16270. Camera.prototype.serialize = function () {
  16271. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16272. // Type
  16273. serializationObject.type = this.getClassName();
  16274. // Parent
  16275. if (this.parent) {
  16276. serializationObject.parentId = this.parent.id;
  16277. }
  16278. if (this.inputs) {
  16279. this.inputs.serialize(serializationObject);
  16280. }
  16281. // Animations
  16282. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16283. serializationObject.ranges = this.serializeAnimationRanges();
  16284. return serializationObject;
  16285. };
  16286. Camera.prototype.clone = function (name) {
  16287. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16288. };
  16289. Camera.prototype.getDirection = function (localAxis) {
  16290. var result = BABYLON.Vector3.Zero();
  16291. this.getDirectionToRef(localAxis, result);
  16292. return result;
  16293. };
  16294. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16295. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16296. };
  16297. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16298. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16299. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16300. switch (type) {
  16301. case "ArcRotateCamera":
  16302. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16303. case "DeviceOrientationCamera":
  16304. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16305. case "FollowCamera":
  16306. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16307. case "ArcFollowCamera":
  16308. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16309. case "GamepadCamera":
  16310. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16311. case "TouchCamera":
  16312. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16313. case "VirtualJoysticksCamera":
  16314. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16315. case "WebVRFreeCamera":
  16316. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16317. case "WebVRGamepadCamera":
  16318. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16319. case "VRDeviceOrientationFreeCamera":
  16320. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16321. case "VRDeviceOrientationGamepadCamera":
  16322. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16323. case "AnaglyphArcRotateCamera":
  16324. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16325. case "AnaglyphFreeCamera":
  16326. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16327. case "AnaglyphGamepadCamera":
  16328. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16329. case "AnaglyphUniversalCamera":
  16330. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16331. case "StereoscopicArcRotateCamera":
  16332. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16333. case "StereoscopicFreeCamera":
  16334. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16335. case "StereoscopicGamepadCamera":
  16336. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16337. case "StereoscopicUniversalCamera":
  16338. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16339. case "FreeCamera":// Forcing Universal here
  16340. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16341. default:// Universal Camera is the default value
  16342. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16343. }
  16344. };
  16345. Camera.Parse = function (parsedCamera, scene) {
  16346. var type = parsedCamera.type;
  16347. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16348. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16349. // Parent
  16350. if (parsedCamera.parentId) {
  16351. camera._waitingParentId = parsedCamera.parentId;
  16352. }
  16353. //If camera has an input manager, let it parse inputs settings
  16354. if (camera.inputs) {
  16355. camera.inputs.parse(parsedCamera);
  16356. camera._setupInputs();
  16357. }
  16358. if (camera.setPosition) {
  16359. camera.position.copyFromFloats(0, 0, 0);
  16360. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16361. }
  16362. // Target
  16363. if (parsedCamera.target) {
  16364. if (camera.setTarget) {
  16365. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16366. }
  16367. }
  16368. // Apply 3d rig, when found
  16369. if (parsedCamera.cameraRigMode) {
  16370. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16371. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16372. }
  16373. // Animations
  16374. if (parsedCamera.animations) {
  16375. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16376. var parsedAnimation = parsedCamera.animations[animationIndex];
  16377. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16378. }
  16379. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16380. }
  16381. if (parsedCamera.autoAnimate) {
  16382. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16383. }
  16384. return camera;
  16385. };
  16386. // Statics
  16387. Camera._PERSPECTIVE_CAMERA = 0;
  16388. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16389. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16390. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16391. Camera._RIG_MODE_NONE = 0;
  16392. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16393. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16394. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16395. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16396. Camera._RIG_MODE_VR = 20;
  16397. Camera._RIG_MODE_WEBVR = 21;
  16398. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16399. Camera.UseAlternateWebVRRendering = false;
  16400. __decorate([
  16401. BABYLON.serializeAsVector3()
  16402. ], Camera.prototype, "position", void 0);
  16403. __decorate([
  16404. BABYLON.serializeAsVector3()
  16405. ], Camera.prototype, "upVector", void 0);
  16406. __decorate([
  16407. BABYLON.serialize()
  16408. ], Camera.prototype, "orthoLeft", void 0);
  16409. __decorate([
  16410. BABYLON.serialize()
  16411. ], Camera.prototype, "orthoRight", void 0);
  16412. __decorate([
  16413. BABYLON.serialize()
  16414. ], Camera.prototype, "orthoBottom", void 0);
  16415. __decorate([
  16416. BABYLON.serialize()
  16417. ], Camera.prototype, "orthoTop", void 0);
  16418. __decorate([
  16419. BABYLON.serialize()
  16420. ], Camera.prototype, "fov", void 0);
  16421. __decorate([
  16422. BABYLON.serialize()
  16423. ], Camera.prototype, "minZ", void 0);
  16424. __decorate([
  16425. BABYLON.serialize()
  16426. ], Camera.prototype, "maxZ", void 0);
  16427. __decorate([
  16428. BABYLON.serialize()
  16429. ], Camera.prototype, "inertia", void 0);
  16430. __decorate([
  16431. BABYLON.serialize()
  16432. ], Camera.prototype, "mode", void 0);
  16433. __decorate([
  16434. BABYLON.serialize()
  16435. ], Camera.prototype, "layerMask", void 0);
  16436. __decorate([
  16437. BABYLON.serialize()
  16438. ], Camera.prototype, "fovMode", void 0);
  16439. __decorate([
  16440. BABYLON.serialize()
  16441. ], Camera.prototype, "cameraRigMode", void 0);
  16442. __decorate([
  16443. BABYLON.serialize()
  16444. ], Camera.prototype, "interaxialDistance", void 0);
  16445. __decorate([
  16446. BABYLON.serialize()
  16447. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16448. return Camera;
  16449. }(BABYLON.Node));
  16450. BABYLON.Camera = Camera;
  16451. })(BABYLON || (BABYLON = {}));
  16452. //# sourceMappingURL=babylon.camera.js.map
  16453. var BABYLON;
  16454. (function (BABYLON) {
  16455. var RenderingManager = /** @class */ (function () {
  16456. function RenderingManager(scene) {
  16457. this._renderingGroups = new Array();
  16458. this._autoClearDepthStencil = {};
  16459. this._customOpaqueSortCompareFn = {};
  16460. this._customAlphaTestSortCompareFn = {};
  16461. this._customTransparentSortCompareFn = {};
  16462. this._renderinGroupInfo = null;
  16463. this._scene = scene;
  16464. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16465. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16466. }
  16467. }
  16468. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16469. if (depth === void 0) { depth = true; }
  16470. if (stencil === void 0) { stencil = true; }
  16471. if (this._depthStencilBufferAlreadyCleaned) {
  16472. return;
  16473. }
  16474. this._scene.getEngine().clear(null, false, depth, stencil);
  16475. this._depthStencilBufferAlreadyCleaned = true;
  16476. };
  16477. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16478. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16479. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16480. var info = null;
  16481. if (observable) {
  16482. if (!this._renderinGroupInfo) {
  16483. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16484. }
  16485. info = this._renderinGroupInfo;
  16486. info.scene = this._scene;
  16487. info.camera = this._scene.activeCamera;
  16488. }
  16489. // Dispatch sprites
  16490. if (renderSprites) {
  16491. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16492. var manager = this._scene.spriteManagers[index];
  16493. this.dispatchSprites(manager);
  16494. }
  16495. }
  16496. // Render
  16497. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16498. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16499. var renderingGroup = this._renderingGroups[index];
  16500. if (!renderingGroup && !observable)
  16501. continue;
  16502. this._currentIndex = index;
  16503. var renderingGroupMask = 0;
  16504. // Fire PRECLEAR stage
  16505. if (observable && info) {
  16506. renderingGroupMask = Math.pow(2, index);
  16507. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16508. info.renderingGroupId = index;
  16509. observable.notifyObservers(info, renderingGroupMask);
  16510. }
  16511. // Clear depth/stencil if needed
  16512. if (RenderingManager.AUTOCLEAR) {
  16513. var autoClear = this._autoClearDepthStencil[index];
  16514. if (autoClear && autoClear.autoClear) {
  16515. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16516. }
  16517. }
  16518. if (observable && info) {
  16519. // Fire PREOPAQUE stage
  16520. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16521. observable.notifyObservers(info, renderingGroupMask);
  16522. // Fire PRETRANSPARENT stage
  16523. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16524. observable.notifyObservers(info, renderingGroupMask);
  16525. }
  16526. if (renderingGroup)
  16527. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16528. // Fire POSTTRANSPARENT stage
  16529. if (observable && info) {
  16530. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16531. observable.notifyObservers(info, renderingGroupMask);
  16532. }
  16533. }
  16534. };
  16535. RenderingManager.prototype.reset = function () {
  16536. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16537. var renderingGroup = this._renderingGroups[index];
  16538. if (renderingGroup) {
  16539. renderingGroup.prepare();
  16540. }
  16541. }
  16542. };
  16543. RenderingManager.prototype.dispose = function () {
  16544. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16545. var renderingGroup = this._renderingGroups[index];
  16546. if (renderingGroup) {
  16547. renderingGroup.dispose();
  16548. }
  16549. }
  16550. this._renderingGroups.length = 0;
  16551. };
  16552. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16553. if (!this._renderingGroups[renderingGroupId]) {
  16554. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16555. }
  16556. };
  16557. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16558. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16559. this._prepareRenderingGroup(renderingGroupId);
  16560. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16561. };
  16562. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16563. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16564. this._prepareRenderingGroup(renderingGroupId);
  16565. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16566. };
  16567. RenderingManager.prototype.dispatch = function (subMesh) {
  16568. var mesh = subMesh.getMesh();
  16569. var renderingGroupId = mesh.renderingGroupId || 0;
  16570. this._prepareRenderingGroup(renderingGroupId);
  16571. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16572. };
  16573. /**
  16574. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16575. * This allowed control for front to back rendering or reversly depending of the special needs.
  16576. *
  16577. * @param renderingGroupId The rendering group id corresponding to its index
  16578. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16579. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16580. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16581. */
  16582. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16583. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16584. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16585. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16586. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16587. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16588. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16589. if (this._renderingGroups[renderingGroupId]) {
  16590. var group = this._renderingGroups[renderingGroupId];
  16591. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16592. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16593. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16594. }
  16595. };
  16596. /**
  16597. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16598. *
  16599. * @param renderingGroupId The rendering group id corresponding to its index
  16600. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16601. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16602. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16603. */
  16604. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16605. if (depth === void 0) { depth = true; }
  16606. if (stencil === void 0) { stencil = true; }
  16607. this._autoClearDepthStencil[renderingGroupId] = {
  16608. autoClear: autoClearDepthStencil,
  16609. depth: depth,
  16610. stencil: stencil
  16611. };
  16612. };
  16613. /**
  16614. * The max id used for rendering groups (not included)
  16615. */
  16616. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16617. /**
  16618. * The min id used for rendering groups (included)
  16619. */
  16620. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16621. /**
  16622. * Used to globally prevent autoclearing scenes.
  16623. */
  16624. RenderingManager.AUTOCLEAR = true;
  16625. return RenderingManager;
  16626. }());
  16627. BABYLON.RenderingManager = RenderingManager;
  16628. })(BABYLON || (BABYLON = {}));
  16629. //# sourceMappingURL=babylon.renderingManager.js.map
  16630. var BABYLON;
  16631. (function (BABYLON) {
  16632. var RenderingGroup = /** @class */ (function () {
  16633. /**
  16634. * Creates a new rendering group.
  16635. * @param index The rendering group index
  16636. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16637. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16638. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16639. */
  16640. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16641. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16642. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16643. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16644. this.index = index;
  16645. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16646. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16647. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16648. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16649. this._particleSystems = new BABYLON.SmartArray(256);
  16650. this._spriteManagers = new BABYLON.SmartArray(256);
  16651. this._edgesRenderers = new BABYLON.SmartArray(16);
  16652. this._scene = scene;
  16653. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16654. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16655. this.transparentSortCompareFn = transparentSortCompareFn;
  16656. }
  16657. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16658. /**
  16659. * Set the opaque sort comparison function.
  16660. * If null the sub meshes will be render in the order they were created
  16661. */
  16662. set: function (value) {
  16663. this._opaqueSortCompareFn = value;
  16664. if (value) {
  16665. this._renderOpaque = this.renderOpaqueSorted;
  16666. }
  16667. else {
  16668. this._renderOpaque = RenderingGroup.renderUnsorted;
  16669. }
  16670. },
  16671. enumerable: true,
  16672. configurable: true
  16673. });
  16674. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16675. /**
  16676. * Set the alpha test sort comparison function.
  16677. * If null the sub meshes will be render in the order they were created
  16678. */
  16679. set: function (value) {
  16680. this._alphaTestSortCompareFn = value;
  16681. if (value) {
  16682. this._renderAlphaTest = this.renderAlphaTestSorted;
  16683. }
  16684. else {
  16685. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16686. }
  16687. },
  16688. enumerable: true,
  16689. configurable: true
  16690. });
  16691. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16692. /**
  16693. * Set the transparent sort comparison function.
  16694. * If null the sub meshes will be render in the order they were created
  16695. */
  16696. set: function (value) {
  16697. if (value) {
  16698. this._transparentSortCompareFn = value;
  16699. }
  16700. else {
  16701. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16702. }
  16703. this._renderTransparent = this.renderTransparentSorted;
  16704. },
  16705. enumerable: true,
  16706. configurable: true
  16707. });
  16708. /**
  16709. * Render all the sub meshes contained in the group.
  16710. * @param customRenderFunction Used to override the default render behaviour of the group.
  16711. * @returns true if rendered some submeshes.
  16712. */
  16713. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16714. if (customRenderFunction) {
  16715. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16716. return;
  16717. }
  16718. var engine = this._scene.getEngine();
  16719. // Depth only
  16720. if (this._depthOnlySubMeshes.length !== 0) {
  16721. engine.setAlphaTesting(true);
  16722. engine.setColorWrite(false);
  16723. this._renderAlphaTest(this._depthOnlySubMeshes);
  16724. engine.setAlphaTesting(false);
  16725. engine.setColorWrite(true);
  16726. }
  16727. // Opaque
  16728. if (this._opaqueSubMeshes.length !== 0) {
  16729. this._renderOpaque(this._opaqueSubMeshes);
  16730. }
  16731. // Alpha test
  16732. if (this._alphaTestSubMeshes.length !== 0) {
  16733. engine.setAlphaTesting(true);
  16734. this._renderAlphaTest(this._alphaTestSubMeshes);
  16735. engine.setAlphaTesting(false);
  16736. }
  16737. var stencilState = engine.getStencilBuffer();
  16738. engine.setStencilBuffer(false);
  16739. // Sprites
  16740. if (renderSprites) {
  16741. this._renderSprites();
  16742. }
  16743. // Particles
  16744. if (renderParticles) {
  16745. this._renderParticles(activeMeshes);
  16746. }
  16747. if (this.onBeforeTransparentRendering) {
  16748. this.onBeforeTransparentRendering();
  16749. }
  16750. // Transparent
  16751. if (this._transparentSubMeshes.length !== 0) {
  16752. this._renderTransparent(this._transparentSubMeshes);
  16753. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16754. }
  16755. // Set back stencil to false in case it changes before the edge renderer.
  16756. engine.setStencilBuffer(false);
  16757. // Edges
  16758. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16759. this._edgesRenderers.data[edgesRendererIndex].render();
  16760. }
  16761. // Restore Stencil state.
  16762. engine.setStencilBuffer(stencilState);
  16763. };
  16764. /**
  16765. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16766. * @param subMeshes The submeshes to render
  16767. */
  16768. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16769. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  16770. };
  16771. /**
  16772. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16773. * @param subMeshes The submeshes to render
  16774. */
  16775. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16776. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  16777. };
  16778. /**
  16779. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16780. * @param subMeshes The submeshes to render
  16781. */
  16782. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16783. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  16784. };
  16785. /**
  16786. * Renders the submeshes in a specified order.
  16787. * @param subMeshes The submeshes to sort before render
  16788. * @param sortCompareFn The comparison function use to sort
  16789. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16790. * @param transparent Specifies to activate blending if true
  16791. */
  16792. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  16793. var subIndex = 0;
  16794. var subMesh;
  16795. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  16796. for (; subIndex < subMeshes.length; subIndex++) {
  16797. subMesh = subMeshes.data[subIndex];
  16798. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16799. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16800. }
  16801. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16802. if (sortCompareFn) {
  16803. sortedArray.sort(sortCompareFn);
  16804. }
  16805. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16806. subMesh = sortedArray[subIndex];
  16807. if (transparent) {
  16808. var material = subMesh.getMaterial();
  16809. if (material && material.needDepthPrePass) {
  16810. var engine = material.getScene().getEngine();
  16811. engine.setColorWrite(false);
  16812. engine.setAlphaTesting(true);
  16813. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16814. subMesh.render(false);
  16815. engine.setAlphaTesting(false);
  16816. engine.setColorWrite(true);
  16817. }
  16818. }
  16819. subMesh.render(transparent);
  16820. }
  16821. };
  16822. /**
  16823. * Renders the submeshes in the order they were dispatched (no sort applied).
  16824. * @param subMeshes The submeshes to render
  16825. */
  16826. RenderingGroup.renderUnsorted = function (subMeshes) {
  16827. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16828. var submesh = subMeshes.data[subIndex];
  16829. submesh.render(false);
  16830. }
  16831. };
  16832. /**
  16833. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16834. * are rendered back to front if in the same alpha index.
  16835. *
  16836. * @param a The first submesh
  16837. * @param b The second submesh
  16838. * @returns The result of the comparison
  16839. */
  16840. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16841. // Alpha index first
  16842. if (a._alphaIndex > b._alphaIndex) {
  16843. return 1;
  16844. }
  16845. if (a._alphaIndex < b._alphaIndex) {
  16846. return -1;
  16847. }
  16848. // Then distance to camera
  16849. return RenderingGroup.backToFrontSortCompare(a, b);
  16850. };
  16851. /**
  16852. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16853. * are rendered back to front.
  16854. *
  16855. * @param a The first submesh
  16856. * @param b The second submesh
  16857. * @returns The result of the comparison
  16858. */
  16859. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16860. // Then distance to camera
  16861. if (a._distanceToCamera < b._distanceToCamera) {
  16862. return 1;
  16863. }
  16864. if (a._distanceToCamera > b._distanceToCamera) {
  16865. return -1;
  16866. }
  16867. return 0;
  16868. };
  16869. /**
  16870. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16871. * are rendered front to back (prevent overdraw).
  16872. *
  16873. * @param a The first submesh
  16874. * @param b The second submesh
  16875. * @returns The result of the comparison
  16876. */
  16877. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16878. // Then distance to camera
  16879. if (a._distanceToCamera < b._distanceToCamera) {
  16880. return -1;
  16881. }
  16882. if (a._distanceToCamera > b._distanceToCamera) {
  16883. return 1;
  16884. }
  16885. return 0;
  16886. };
  16887. /**
  16888. * Resets the different lists of submeshes to prepare a new frame.
  16889. */
  16890. RenderingGroup.prototype.prepare = function () {
  16891. this._opaqueSubMeshes.reset();
  16892. this._transparentSubMeshes.reset();
  16893. this._alphaTestSubMeshes.reset();
  16894. this._depthOnlySubMeshes.reset();
  16895. this._particleSystems.reset();
  16896. this._spriteManagers.reset();
  16897. this._edgesRenderers.reset();
  16898. };
  16899. RenderingGroup.prototype.dispose = function () {
  16900. this._opaqueSubMeshes.dispose();
  16901. this._transparentSubMeshes.dispose();
  16902. this._alphaTestSubMeshes.dispose();
  16903. this._depthOnlySubMeshes.dispose();
  16904. this._particleSystems.dispose();
  16905. this._spriteManagers.dispose();
  16906. this._edgesRenderers.dispose();
  16907. };
  16908. /**
  16909. * Inserts the submesh in its correct queue depending on its material.
  16910. * @param subMesh The submesh to dispatch
  16911. */
  16912. RenderingGroup.prototype.dispatch = function (subMesh) {
  16913. var material = subMesh.getMaterial();
  16914. var mesh = subMesh.getMesh();
  16915. if (!material) {
  16916. return;
  16917. }
  16918. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16919. this._transparentSubMeshes.push(subMesh);
  16920. }
  16921. else if (material.needAlphaTesting()) {
  16922. if (material.needDepthPrePass) {
  16923. this._depthOnlySubMeshes.push(subMesh);
  16924. }
  16925. this._alphaTestSubMeshes.push(subMesh);
  16926. }
  16927. else {
  16928. if (material.needDepthPrePass) {
  16929. this._depthOnlySubMeshes.push(subMesh);
  16930. }
  16931. this._opaqueSubMeshes.push(subMesh); // Opaque
  16932. }
  16933. if (mesh._edgesRenderer) {
  16934. this._edgesRenderers.push(mesh._edgesRenderer);
  16935. }
  16936. };
  16937. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16938. this._spriteManagers.push(spriteManager);
  16939. };
  16940. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16941. this._particleSystems.push(particleSystem);
  16942. };
  16943. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16944. if (this._particleSystems.length === 0) {
  16945. return;
  16946. }
  16947. // Particles
  16948. var activeCamera = this._scene.activeCamera;
  16949. this._scene._particlesDuration.beginMonitoring();
  16950. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16951. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16952. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16953. continue;
  16954. }
  16955. var emitter = particleSystem.emitter;
  16956. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16957. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16958. }
  16959. }
  16960. this._scene._particlesDuration.endMonitoring(false);
  16961. };
  16962. RenderingGroup.prototype._renderSprites = function () {
  16963. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16964. return;
  16965. }
  16966. // Sprites
  16967. var activeCamera = this._scene.activeCamera;
  16968. this._scene._spritesDuration.beginMonitoring();
  16969. for (var id = 0; id < this._spriteManagers.length; id++) {
  16970. var spriteManager = this._spriteManagers.data[id];
  16971. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16972. spriteManager.render();
  16973. }
  16974. }
  16975. this._scene._spritesDuration.endMonitoring(false);
  16976. };
  16977. return RenderingGroup;
  16978. }());
  16979. BABYLON.RenderingGroup = RenderingGroup;
  16980. })(BABYLON || (BABYLON = {}));
  16981. //# sourceMappingURL=babylon.renderingGroup.js.map
  16982. var BABYLON;
  16983. (function (BABYLON) {
  16984. var ClickInfo = /** @class */ (function () {
  16985. function ClickInfo() {
  16986. this._singleClick = false;
  16987. this._doubleClick = false;
  16988. this._hasSwiped = false;
  16989. this._ignore = false;
  16990. }
  16991. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16992. get: function () {
  16993. return this._singleClick;
  16994. },
  16995. set: function (b) {
  16996. this._singleClick = b;
  16997. },
  16998. enumerable: true,
  16999. configurable: true
  17000. });
  17001. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17002. get: function () {
  17003. return this._doubleClick;
  17004. },
  17005. set: function (b) {
  17006. this._doubleClick = b;
  17007. },
  17008. enumerable: true,
  17009. configurable: true
  17010. });
  17011. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17012. get: function () {
  17013. return this._hasSwiped;
  17014. },
  17015. set: function (b) {
  17016. this._hasSwiped = b;
  17017. },
  17018. enumerable: true,
  17019. configurable: true
  17020. });
  17021. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17022. get: function () {
  17023. return this._ignore;
  17024. },
  17025. set: function (b) {
  17026. this._ignore = b;
  17027. },
  17028. enumerable: true,
  17029. configurable: true
  17030. });
  17031. return ClickInfo;
  17032. }());
  17033. /**
  17034. * This class is used by the onRenderingGroupObservable
  17035. */
  17036. var RenderingGroupInfo = /** @class */ (function () {
  17037. function RenderingGroupInfo() {
  17038. }
  17039. /**
  17040. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17041. * This stage will be fired no matter what
  17042. */
  17043. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17044. /**
  17045. * Called before opaque object are rendered.
  17046. * This stage will be fired only if there's 3D Opaque content to render
  17047. */
  17048. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17049. /**
  17050. * Called after the opaque objects are rendered and before the transparent ones
  17051. * This stage will be fired only if there's 3D transparent content to render
  17052. */
  17053. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17054. /**
  17055. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17056. * This stage will be fired no matter what
  17057. */
  17058. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17059. return RenderingGroupInfo;
  17060. }());
  17061. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17062. /**
  17063. * Represents a scene to be rendered by the engine.
  17064. * @see http://doc.babylonjs.com/page.php?p=21911
  17065. */
  17066. var Scene = /** @class */ (function () {
  17067. /**
  17068. * @constructor
  17069. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17070. */
  17071. function Scene(engine) {
  17072. // Members
  17073. this.autoClear = true;
  17074. this.autoClearDepthAndStencil = true;
  17075. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17076. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17077. this.forceWireframe = false;
  17078. this._forcePointsCloud = false;
  17079. this.forceShowBoundingBoxes = false;
  17080. this.animationsEnabled = true;
  17081. this.constantlyUpdateMeshUnderPointer = false;
  17082. this.hoverCursor = "pointer";
  17083. this.defaultCursor = "";
  17084. /**
  17085. * This is used to call preventDefault() on pointer down
  17086. * in order to block unwanted artifacts like system double clicks
  17087. */
  17088. this.preventDefaultOnPointerDown = true;
  17089. // Metadata
  17090. this.metadata = null;
  17091. /**
  17092. * An event triggered when the scene is disposed.
  17093. * @type {BABYLON.Observable}
  17094. */
  17095. this.onDisposeObservable = new BABYLON.Observable();
  17096. /**
  17097. * An event triggered before rendering the scene
  17098. * @type {BABYLON.Observable}
  17099. */
  17100. this.onBeforeRenderObservable = new BABYLON.Observable();
  17101. /**
  17102. * An event triggered after rendering the scene
  17103. * @type {BABYLON.Observable}
  17104. */
  17105. this.onAfterRenderObservable = new BABYLON.Observable();
  17106. /**
  17107. * An event triggered when the scene is ready
  17108. * @type {BABYLON.Observable}
  17109. */
  17110. this.onReadyObservable = new BABYLON.Observable();
  17111. /**
  17112. * An event triggered before rendering a camera
  17113. * @type {BABYLON.Observable}
  17114. */
  17115. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17116. /**
  17117. * An event triggered after rendering a camera
  17118. * @type {BABYLON.Observable}
  17119. */
  17120. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17121. /**
  17122. * An event triggered when a camera is created
  17123. * @type {BABYLON.Observable}
  17124. */
  17125. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17126. /**
  17127. * An event triggered when a camera is removed
  17128. * @type {BABYLON.Observable}
  17129. */
  17130. this.onCameraRemovedObservable = new BABYLON.Observable();
  17131. /**
  17132. * An event triggered when a light is created
  17133. * @type {BABYLON.Observable}
  17134. */
  17135. this.onNewLightAddedObservable = new BABYLON.Observable();
  17136. /**
  17137. * An event triggered when a light is removed
  17138. * @type {BABYLON.Observable}
  17139. */
  17140. this.onLightRemovedObservable = new BABYLON.Observable();
  17141. /**
  17142. * An event triggered when a geometry is created
  17143. * @type {BABYLON.Observable}
  17144. */
  17145. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17146. /**
  17147. * An event triggered when a geometry is removed
  17148. * @type {BABYLON.Observable}
  17149. */
  17150. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17151. /**
  17152. * An event triggered when a mesh is created
  17153. * @type {BABYLON.Observable}
  17154. */
  17155. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17156. /**
  17157. * An event triggered when a mesh is removed
  17158. * @type {BABYLON.Observable}
  17159. */
  17160. this.onMeshRemovedObservable = new BABYLON.Observable();
  17161. /**
  17162. * An event triggered before calculating deterministic simulation step
  17163. * @type {BABYLON.Observable}
  17164. */
  17165. this.onBeforeStepObservable = new BABYLON.Observable();
  17166. /**
  17167. * An event triggered after calculating deterministic simulation step
  17168. * @type {BABYLON.Observable}
  17169. */
  17170. this.onAfterStepObservable = new BABYLON.Observable();
  17171. /**
  17172. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17173. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17174. * 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)
  17175. */
  17176. this.onRenderingGroupObservable = new BABYLON.Observable();
  17177. // Animations
  17178. this.animations = [];
  17179. /**
  17180. * 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).
  17181. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17182. */
  17183. this.onPrePointerObservable = new BABYLON.Observable();
  17184. /**
  17185. * Observable event triggered each time an input event is received from the rendering canvas
  17186. */
  17187. this.onPointerObservable = new BABYLON.Observable();
  17188. this._meshPickProceed = false;
  17189. this._previousHasSwiped = false;
  17190. this._currentPickResult = null;
  17191. this._previousPickResult = null;
  17192. this._totalPointersPressed = 0;
  17193. this._doubleClickOccured = false;
  17194. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17195. this.cameraToUseForPointers = null;
  17196. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17197. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17198. this._startingPointerTime = 0;
  17199. this._previousStartingPointerTime = 0;
  17200. // Deterministic lockstep
  17201. this._timeAccumulator = 0;
  17202. this._currentStepId = 0;
  17203. this._currentInternalStep = 0;
  17204. // Keyboard
  17205. /**
  17206. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17207. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17208. */
  17209. this.onPreKeyboardObservable = new BABYLON.Observable();
  17210. /**
  17211. * Observable event triggered each time an keyboard event is received from the hosting window
  17212. */
  17213. this.onKeyboardObservable = new BABYLON.Observable();
  17214. // Coordinate system
  17215. /**
  17216. * use right-handed coordinate system on this scene.
  17217. * @type {boolean}
  17218. */
  17219. this._useRightHandedSystem = false;
  17220. // Fog
  17221. this._fogEnabled = true;
  17222. this._fogMode = Scene.FOGMODE_NONE;
  17223. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17224. this.fogDensity = 0.1;
  17225. this.fogStart = 0;
  17226. this.fogEnd = 1000.0;
  17227. // Lights
  17228. /**
  17229. * is shadow enabled on this scene.
  17230. * @type {boolean}
  17231. */
  17232. this._shadowsEnabled = true;
  17233. /**
  17234. * is light enabled on this scene.
  17235. * @type {boolean}
  17236. */
  17237. this._lightsEnabled = true;
  17238. /**
  17239. * All of the lights added to this scene.
  17240. * @see BABYLON.Light
  17241. * @type {BABYLON.Light[]}
  17242. */
  17243. this.lights = new Array();
  17244. // Cameras
  17245. /** All of the cameras added to this scene. */
  17246. this.cameras = new Array();
  17247. /** All of the active cameras added to this scene. */
  17248. this.activeCameras = new Array();
  17249. // Meshes
  17250. /**
  17251. * All of the (abstract) meshes added to this scene.
  17252. * @see BABYLON.AbstractMesh
  17253. * @type {BABYLON.AbstractMesh[]}
  17254. */
  17255. this.meshes = new Array();
  17256. // Geometries
  17257. this._geometries = new Array();
  17258. this.materials = new Array();
  17259. this.multiMaterials = new Array();
  17260. // Textures
  17261. this._texturesEnabled = true;
  17262. this.textures = new Array();
  17263. // Particles
  17264. this.particlesEnabled = true;
  17265. this.particleSystems = new Array();
  17266. // Sprites
  17267. this.spritesEnabled = true;
  17268. this.spriteManagers = new Array();
  17269. // Layers
  17270. this.layers = new Array();
  17271. this.highlightLayers = new Array();
  17272. // Skeletons
  17273. this._skeletonsEnabled = true;
  17274. this.skeletons = new Array();
  17275. // Morph targets
  17276. this.morphTargetManagers = new Array();
  17277. // Lens flares
  17278. this.lensFlaresEnabled = true;
  17279. this.lensFlareSystems = new Array();
  17280. // Collisions
  17281. this.collisionsEnabled = true;
  17282. /** Defines the gravity applied to this scene */
  17283. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17284. // Postprocesses
  17285. this.postProcesses = new Array();
  17286. this.postProcessesEnabled = true;
  17287. // Customs render targets
  17288. this.renderTargetsEnabled = true;
  17289. this.dumpNextRenderTargets = false;
  17290. this.customRenderTargets = new Array();
  17291. // Imported meshes
  17292. this.importedMeshesFiles = new Array();
  17293. // Probes
  17294. this.probesEnabled = true;
  17295. this.reflectionProbes = new Array();
  17296. this._actionManagers = new Array();
  17297. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17298. // Procedural textures
  17299. this.proceduralTexturesEnabled = true;
  17300. this._proceduralTextures = new Array();
  17301. this.soundTracks = new Array();
  17302. this._audioEnabled = true;
  17303. this._headphone = false;
  17304. // Performance counters
  17305. this._totalMeshesCounter = new BABYLON.PerfCounter();
  17306. this._totalLightsCounter = new BABYLON.PerfCounter();
  17307. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  17308. this._totalTexturesCounter = new BABYLON.PerfCounter();
  17309. this._totalVertices = new BABYLON.PerfCounter();
  17310. this._activeIndices = new BABYLON.PerfCounter();
  17311. this._activeParticles = new BABYLON.PerfCounter();
  17312. this._interFrameDuration = new BABYLON.PerfCounter();
  17313. this._lastFrameDuration = new BABYLON.PerfCounter();
  17314. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  17315. this._renderTargetsDuration = new BABYLON.PerfCounter();
  17316. this._particlesDuration = new BABYLON.PerfCounter();
  17317. this._renderDuration = new BABYLON.PerfCounter();
  17318. this._spritesDuration = new BABYLON.PerfCounter();
  17319. this._activeBones = new BABYLON.PerfCounter();
  17320. this._animationTime = 0;
  17321. this.animationTimeScale = 1;
  17322. this._renderId = 0;
  17323. this._executeWhenReadyTimeoutId = -1;
  17324. this._intermediateRendering = false;
  17325. this._viewUpdateFlag = -1;
  17326. this._projectionUpdateFlag = -1;
  17327. this._alternateViewUpdateFlag = -1;
  17328. this._alternateProjectionUpdateFlag = -1;
  17329. this._toBeDisposed = new BABYLON.SmartArray(256);
  17330. this._pendingData = new Array();
  17331. this._isDisposed = false;
  17332. this._activeMeshes = new BABYLON.SmartArray(256);
  17333. this._processedMaterials = new BABYLON.SmartArray(256);
  17334. this._renderTargets = new BABYLON.SmartArray(256);
  17335. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17336. this._activeSkeletons = new BABYLON.SmartArray(32);
  17337. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17338. this._activeAnimatables = new Array();
  17339. this._transformMatrix = BABYLON.Matrix.Zero();
  17340. this._useAlternateCameraConfiguration = false;
  17341. this._alternateRendering = false;
  17342. this.requireLightSorting = false;
  17343. this._activeMeshesFrozen = false;
  17344. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17345. this._engine.scenes.push(this);
  17346. this._uid = null;
  17347. this._renderingManager = new BABYLON.RenderingManager(this);
  17348. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17349. if (BABYLON.OutlineRenderer) {
  17350. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17351. }
  17352. if (BABYLON.Tools.IsWindowObjectExist()) {
  17353. this.attachControl();
  17354. }
  17355. //simplification queue
  17356. if (BABYLON.SimplificationQueue) {
  17357. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17358. }
  17359. //collision coordinator initialization. For now legacy per default.
  17360. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17361. // Uniform Buffer
  17362. this._createUbo();
  17363. // Default Image processing definition.
  17364. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17365. }
  17366. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17367. /** The fog is deactivated */
  17368. get: function () {
  17369. return Scene._FOGMODE_NONE;
  17370. },
  17371. enumerable: true,
  17372. configurable: true
  17373. });
  17374. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17375. /** The fog density is following an exponential function */
  17376. get: function () {
  17377. return Scene._FOGMODE_EXP;
  17378. },
  17379. enumerable: true,
  17380. configurable: true
  17381. });
  17382. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17383. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17384. get: function () {
  17385. return Scene._FOGMODE_EXP2;
  17386. },
  17387. enumerable: true,
  17388. configurable: true
  17389. });
  17390. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17391. /** The fog density is following a linear function. */
  17392. get: function () {
  17393. return Scene._FOGMODE_LINEAR;
  17394. },
  17395. enumerable: true,
  17396. configurable: true
  17397. });
  17398. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17399. /**
  17400. * Texture used in all pbr material as the reflection texture.
  17401. * As in the majority of the scene they are the same (exception for multi room and so on),
  17402. * this is easier to reference from here than from all the materials.
  17403. */
  17404. get: function () {
  17405. return this._environmentTexture;
  17406. },
  17407. /**
  17408. * Texture used in all pbr material as the reflection texture.
  17409. * As in the majority of the scene they are the same (exception for multi room and so on),
  17410. * this is easier to set here than in all the materials.
  17411. */
  17412. set: function (value) {
  17413. if (this._environmentTexture === value) {
  17414. return;
  17415. }
  17416. this._environmentTexture = value;
  17417. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17418. },
  17419. enumerable: true,
  17420. configurable: true
  17421. });
  17422. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17423. /**
  17424. * Default image processing configuration used either in the rendering
  17425. * Forward main pass or through the imageProcessingPostProcess if present.
  17426. * As in the majority of the scene they are the same (exception for multi camera),
  17427. * this is easier to reference from here than from all the materials and post process.
  17428. *
  17429. * No setter as we it is a shared configuration, you can set the values instead.
  17430. */
  17431. get: function () {
  17432. return this._imageProcessingConfiguration;
  17433. },
  17434. enumerable: true,
  17435. configurable: true
  17436. });
  17437. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17438. get: function () {
  17439. return this._forcePointsCloud;
  17440. },
  17441. set: function (value) {
  17442. if (this._forcePointsCloud === value) {
  17443. return;
  17444. }
  17445. this._forcePointsCloud = value;
  17446. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17447. },
  17448. enumerable: true,
  17449. configurable: true
  17450. });
  17451. Object.defineProperty(Scene.prototype, "onDispose", {
  17452. /** A function to be executed when this scene is disposed. */
  17453. set: function (callback) {
  17454. if (this._onDisposeObserver) {
  17455. this.onDisposeObservable.remove(this._onDisposeObserver);
  17456. }
  17457. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17458. },
  17459. enumerable: true,
  17460. configurable: true
  17461. });
  17462. Object.defineProperty(Scene.prototype, "beforeRender", {
  17463. /** A function to be executed before rendering this scene */
  17464. set: function (callback) {
  17465. if (this._onBeforeRenderObserver) {
  17466. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17467. }
  17468. if (callback) {
  17469. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17470. }
  17471. },
  17472. enumerable: true,
  17473. configurable: true
  17474. });
  17475. Object.defineProperty(Scene.prototype, "afterRender", {
  17476. /** A function to be executed after rendering this scene */
  17477. set: function (callback) {
  17478. if (this._onAfterRenderObserver) {
  17479. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17480. }
  17481. if (callback) {
  17482. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17483. }
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17489. set: function (callback) {
  17490. if (this._onBeforeCameraRenderObserver) {
  17491. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17492. }
  17493. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17494. },
  17495. enumerable: true,
  17496. configurable: true
  17497. });
  17498. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17499. set: function (callback) {
  17500. if (this._onAfterCameraRenderObserver) {
  17501. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17502. }
  17503. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17504. },
  17505. enumerable: true,
  17506. configurable: true
  17507. });
  17508. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17509. get: function () {
  17510. if (!this._gamepadManager) {
  17511. this._gamepadManager = new BABYLON.GamepadManager();
  17512. }
  17513. return this._gamepadManager;
  17514. },
  17515. enumerable: true,
  17516. configurable: true
  17517. });
  17518. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17519. get: function () {
  17520. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17521. },
  17522. enumerable: true,
  17523. configurable: true
  17524. });
  17525. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17526. get: function () {
  17527. return this._useRightHandedSystem;
  17528. },
  17529. set: function (value) {
  17530. if (this._useRightHandedSystem === value) {
  17531. return;
  17532. }
  17533. this._useRightHandedSystem = value;
  17534. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17535. },
  17536. enumerable: true,
  17537. configurable: true
  17538. });
  17539. Scene.prototype.setStepId = function (newStepId) {
  17540. this._currentStepId = newStepId;
  17541. };
  17542. ;
  17543. Scene.prototype.getStepId = function () {
  17544. return this._currentStepId;
  17545. };
  17546. ;
  17547. Scene.prototype.getInternalStep = function () {
  17548. return this._currentInternalStep;
  17549. };
  17550. ;
  17551. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17552. get: function () {
  17553. return this._fogEnabled;
  17554. },
  17555. /**
  17556. * is fog enabled on this scene.
  17557. */
  17558. set: function (value) {
  17559. if (this._fogEnabled === value) {
  17560. return;
  17561. }
  17562. this._fogEnabled = value;
  17563. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17564. },
  17565. enumerable: true,
  17566. configurable: true
  17567. });
  17568. Object.defineProperty(Scene.prototype, "fogMode", {
  17569. get: function () {
  17570. return this._fogMode;
  17571. },
  17572. set: function (value) {
  17573. if (this._fogMode === value) {
  17574. return;
  17575. }
  17576. this._fogMode = value;
  17577. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17578. },
  17579. enumerable: true,
  17580. configurable: true
  17581. });
  17582. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17583. get: function () {
  17584. return this._shadowsEnabled;
  17585. },
  17586. set: function (value) {
  17587. if (this._shadowsEnabled === value) {
  17588. return;
  17589. }
  17590. this._shadowsEnabled = value;
  17591. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17592. },
  17593. enumerable: true,
  17594. configurable: true
  17595. });
  17596. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17597. get: function () {
  17598. return this._lightsEnabled;
  17599. },
  17600. set: function (value) {
  17601. if (this._lightsEnabled === value) {
  17602. return;
  17603. }
  17604. this._lightsEnabled = value;
  17605. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17606. },
  17607. enumerable: true,
  17608. configurable: true
  17609. });
  17610. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17611. /** The default material used on meshes when no material is affected */
  17612. get: function () {
  17613. if (!this._defaultMaterial) {
  17614. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17615. }
  17616. return this._defaultMaterial;
  17617. },
  17618. /** The default material used on meshes when no material is affected */
  17619. set: function (value) {
  17620. this._defaultMaterial = value;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17626. get: function () {
  17627. return this._texturesEnabled;
  17628. },
  17629. set: function (value) {
  17630. if (this._texturesEnabled === value) {
  17631. return;
  17632. }
  17633. this._texturesEnabled = value;
  17634. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17635. },
  17636. enumerable: true,
  17637. configurable: true
  17638. });
  17639. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17640. get: function () {
  17641. return this._skeletonsEnabled;
  17642. },
  17643. set: function (value) {
  17644. if (this._skeletonsEnabled === value) {
  17645. return;
  17646. }
  17647. this._skeletonsEnabled = value;
  17648. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17649. },
  17650. enumerable: true,
  17651. configurable: true
  17652. });
  17653. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17654. get: function () {
  17655. if (!this._postProcessRenderPipelineManager) {
  17656. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17657. }
  17658. return this._postProcessRenderPipelineManager;
  17659. },
  17660. enumerable: true,
  17661. configurable: true
  17662. });
  17663. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17664. get: function () {
  17665. if (!this._mainSoundTrack) {
  17666. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17667. }
  17668. return this._mainSoundTrack;
  17669. },
  17670. enumerable: true,
  17671. configurable: true
  17672. });
  17673. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17674. get: function () {
  17675. return this._alternateRendering;
  17676. },
  17677. enumerable: true,
  17678. configurable: true
  17679. });
  17680. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17681. get: function () {
  17682. return this._frustumPlanes;
  17683. },
  17684. enumerable: true,
  17685. configurable: true
  17686. });
  17687. Object.defineProperty(Scene.prototype, "debugLayer", {
  17688. // Properties
  17689. get: function () {
  17690. if (!this._debugLayer) {
  17691. this._debugLayer = new BABYLON.DebugLayer(this);
  17692. }
  17693. return this._debugLayer;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17699. get: function () {
  17700. return this._workerCollisions;
  17701. },
  17702. set: function (enabled) {
  17703. if (!BABYLON.CollisionCoordinatorLegacy) {
  17704. return;
  17705. }
  17706. enabled = (enabled && !!Worker);
  17707. this._workerCollisions = enabled;
  17708. if (this.collisionCoordinator) {
  17709. this.collisionCoordinator.destroy();
  17710. }
  17711. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17712. this.collisionCoordinator.init(this);
  17713. },
  17714. enumerable: true,
  17715. configurable: true
  17716. });
  17717. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17718. get: function () {
  17719. return this._selectionOctree;
  17720. },
  17721. enumerable: true,
  17722. configurable: true
  17723. });
  17724. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17725. /**
  17726. * The mesh that is currently under the pointer.
  17727. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17728. */
  17729. get: function () {
  17730. return this._pointerOverMesh;
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. Object.defineProperty(Scene.prototype, "pointerX", {
  17736. /**
  17737. * Current on-screen X position of the pointer
  17738. * @return {number} X position of the pointer
  17739. */
  17740. get: function () {
  17741. return this._pointerX;
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(Scene.prototype, "pointerY", {
  17747. /**
  17748. * Current on-screen Y position of the pointer
  17749. * @return {number} Y position of the pointer
  17750. */
  17751. get: function () {
  17752. return this._pointerY;
  17753. },
  17754. enumerable: true,
  17755. configurable: true
  17756. });
  17757. Scene.prototype.getCachedMaterial = function () {
  17758. return this._cachedMaterial;
  17759. };
  17760. Scene.prototype.getCachedEffect = function () {
  17761. return this._cachedEffect;
  17762. };
  17763. Scene.prototype.getCachedVisibility = function () {
  17764. return this._cachedVisibility;
  17765. };
  17766. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17767. if (visibility === void 0) { visibility = 1; }
  17768. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17769. };
  17770. Scene.prototype.getBoundingBoxRenderer = function () {
  17771. if (!this._boundingBoxRenderer) {
  17772. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17773. }
  17774. return this._boundingBoxRenderer;
  17775. };
  17776. Scene.prototype.getOutlineRenderer = function () {
  17777. return this._outlineRenderer;
  17778. };
  17779. Scene.prototype.getEngine = function () {
  17780. return this._engine;
  17781. };
  17782. Scene.prototype.getTotalVertices = function () {
  17783. return this._totalVertices.current;
  17784. };
  17785. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17786. get: function () {
  17787. return this._totalVertices;
  17788. },
  17789. enumerable: true,
  17790. configurable: true
  17791. });
  17792. Scene.prototype.getActiveIndices = function () {
  17793. return this._activeIndices.current;
  17794. };
  17795. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17796. get: function () {
  17797. return this._activeIndices;
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. Scene.prototype.getActiveParticles = function () {
  17803. return this._activeParticles.current;
  17804. };
  17805. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17806. get: function () {
  17807. return this._activeParticles;
  17808. },
  17809. enumerable: true,
  17810. configurable: true
  17811. });
  17812. Scene.prototype.getActiveBones = function () {
  17813. return this._activeBones.current;
  17814. };
  17815. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17816. get: function () {
  17817. return this._activeBones;
  17818. },
  17819. enumerable: true,
  17820. configurable: true
  17821. });
  17822. // Stats
  17823. Scene.prototype.getInterFramePerfCounter = function () {
  17824. return this._interFrameDuration.current;
  17825. };
  17826. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17827. get: function () {
  17828. return this._interFrameDuration;
  17829. },
  17830. enumerable: true,
  17831. configurable: true
  17832. });
  17833. Scene.prototype.getLastFrameDuration = function () {
  17834. return this._lastFrameDuration.current;
  17835. };
  17836. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17837. get: function () {
  17838. return this._lastFrameDuration;
  17839. },
  17840. enumerable: true,
  17841. configurable: true
  17842. });
  17843. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17844. return this._evaluateActiveMeshesDuration.current;
  17845. };
  17846. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17847. get: function () {
  17848. return this._evaluateActiveMeshesDuration;
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Scene.prototype.getActiveMeshes = function () {
  17854. return this._activeMeshes;
  17855. };
  17856. Scene.prototype.getRenderTargetsDuration = function () {
  17857. return this._renderTargetsDuration.current;
  17858. };
  17859. Scene.prototype.getRenderDuration = function () {
  17860. return this._renderDuration.current;
  17861. };
  17862. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17863. get: function () {
  17864. return this._renderDuration;
  17865. },
  17866. enumerable: true,
  17867. configurable: true
  17868. });
  17869. Scene.prototype.getParticlesDuration = function () {
  17870. return this._particlesDuration.current;
  17871. };
  17872. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17873. get: function () {
  17874. return this._particlesDuration;
  17875. },
  17876. enumerable: true,
  17877. configurable: true
  17878. });
  17879. Scene.prototype.getSpritesDuration = function () {
  17880. return this._spritesDuration.current;
  17881. };
  17882. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17883. get: function () {
  17884. return this._spritesDuration;
  17885. },
  17886. enumerable: true,
  17887. configurable: true
  17888. });
  17889. Scene.prototype.getAnimationRatio = function () {
  17890. return this._animationRatio;
  17891. };
  17892. Scene.prototype.getRenderId = function () {
  17893. return this._renderId;
  17894. };
  17895. Scene.prototype.incrementRenderId = function () {
  17896. this._renderId++;
  17897. };
  17898. Scene.prototype._updatePointerPosition = function (evt) {
  17899. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17900. if (!canvasRect) {
  17901. return;
  17902. }
  17903. this._pointerX = evt.clientX - canvasRect.left;
  17904. this._pointerY = evt.clientY - canvasRect.top;
  17905. this._unTranslatedPointerX = this._pointerX;
  17906. this._unTranslatedPointerY = this._pointerY;
  17907. };
  17908. Scene.prototype._createUbo = function () {
  17909. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  17910. this._sceneUbo.addUniform("viewProjection", 16);
  17911. this._sceneUbo.addUniform("view", 16);
  17912. };
  17913. Scene.prototype._createAlternateUbo = function () {
  17914. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  17915. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17916. this._alternateSceneUbo.addUniform("view", 16);
  17917. };
  17918. // Pointers handling
  17919. /**
  17920. * Use this method to simulate a pointer move on a mesh
  17921. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17922. */
  17923. Scene.prototype.simulatePointerMove = function (pickResult) {
  17924. var evt = new PointerEvent("pointermove");
  17925. return this._processPointerMove(pickResult, evt);
  17926. };
  17927. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17928. var canvas = this._engine.getRenderingCanvas();
  17929. if (!canvas) {
  17930. return this;
  17931. }
  17932. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17933. this.setPointerOverSprite(null);
  17934. this.setPointerOverMesh(pickResult.pickedMesh);
  17935. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17936. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17937. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17938. }
  17939. else {
  17940. canvas.style.cursor = this.hoverCursor;
  17941. }
  17942. }
  17943. else {
  17944. canvas.style.cursor = this.defaultCursor;
  17945. }
  17946. }
  17947. else {
  17948. this.setPointerOverMesh(null);
  17949. // Sprites
  17950. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  17951. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17952. this.setPointerOverSprite(pickResult.pickedSprite);
  17953. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17954. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17955. }
  17956. else {
  17957. canvas.style.cursor = this.hoverCursor;
  17958. }
  17959. }
  17960. else {
  17961. this.setPointerOverSprite(null);
  17962. // Restore pointer
  17963. canvas.style.cursor = this.defaultCursor;
  17964. }
  17965. }
  17966. if (pickResult) {
  17967. if (this.onPointerMove) {
  17968. this.onPointerMove(evt, pickResult);
  17969. }
  17970. if (this.onPointerObservable.hasObservers()) {
  17971. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17972. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17973. this.onPointerObservable.notifyObservers(pi, type);
  17974. }
  17975. }
  17976. return this;
  17977. };
  17978. /**
  17979. * Use this method to simulate a pointer down on a mesh
  17980. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17981. */
  17982. Scene.prototype.simulatePointerDown = function (pickResult) {
  17983. var evt = new PointerEvent("pointerdown");
  17984. return this._processPointerDown(pickResult, evt);
  17985. };
  17986. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17987. var _this = this;
  17988. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17989. this._pickedDownMesh = pickResult.pickedMesh;
  17990. var actionManager = pickResult.pickedMesh.actionManager;
  17991. if (actionManager) {
  17992. if (actionManager.hasPickTriggers) {
  17993. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17994. switch (evt.button) {
  17995. case 0:
  17996. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17997. break;
  17998. case 1:
  17999. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18000. break;
  18001. case 2:
  18002. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18003. break;
  18004. }
  18005. }
  18006. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18007. window.setTimeout(function () {
  18008. 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);
  18009. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18010. if (_this._totalPointersPressed !== 0 &&
  18011. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18012. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18013. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18014. _this._startingPointerTime = 0;
  18015. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18016. }
  18017. }
  18018. }, Scene.LongPressDelay);
  18019. }
  18020. }
  18021. }
  18022. if (pickResult) {
  18023. if (this.onPointerDown) {
  18024. this.onPointerDown(evt, pickResult);
  18025. }
  18026. if (this.onPointerObservable.hasObservers()) {
  18027. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18028. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18029. this.onPointerObservable.notifyObservers(pi, type);
  18030. }
  18031. }
  18032. return this;
  18033. };
  18034. /**
  18035. * Use this method to simulate a pointer up on a mesh
  18036. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18037. */
  18038. Scene.prototype.simulatePointerUp = function (pickResult) {
  18039. var evt = new PointerEvent("pointerup");
  18040. var clickInfo = new ClickInfo();
  18041. clickInfo.singleClick = true;
  18042. return this._processPointerUp(pickResult, evt, clickInfo);
  18043. };
  18044. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18045. if (pickResult && pickResult && pickResult.pickedMesh) {
  18046. this._pickedUpMesh = pickResult.pickedMesh;
  18047. if (this._pickedDownMesh === this._pickedUpMesh) {
  18048. if (this.onPointerPick) {
  18049. this.onPointerPick(evt, pickResult);
  18050. }
  18051. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18052. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18053. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18054. this.onPointerObservable.notifyObservers(pi, type);
  18055. }
  18056. }
  18057. if (pickResult.pickedMesh.actionManager) {
  18058. if (clickInfo.ignore) {
  18059. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18060. }
  18061. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18062. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18063. }
  18064. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18065. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18066. }
  18067. }
  18068. }
  18069. if (this._pickedDownMesh &&
  18070. this._pickedDownMesh.actionManager &&
  18071. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18072. this._pickedDownMesh !== this._pickedUpMesh) {
  18073. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18074. }
  18075. if (this.onPointerUp) {
  18076. this.onPointerUp(evt, pickResult);
  18077. }
  18078. if (this.onPointerObservable.hasObservers()) {
  18079. if (!clickInfo.ignore) {
  18080. if (!clickInfo.hasSwiped) {
  18081. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18082. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18083. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18084. this.onPointerObservable.notifyObservers(pi, type);
  18085. }
  18086. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18087. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18088. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18089. this.onPointerObservable.notifyObservers(pi, type);
  18090. }
  18091. }
  18092. }
  18093. else {
  18094. var type = BABYLON.PointerEventTypes.POINTERUP;
  18095. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18096. this.onPointerObservable.notifyObservers(pi, type);
  18097. }
  18098. }
  18099. return this;
  18100. };
  18101. /**
  18102. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18103. * @param attachUp defines if you want to attach events to pointerup
  18104. * @param attachDown defines if you want to attach events to pointerdown
  18105. * @param attachMove defines if you want to attach events to pointermove
  18106. */
  18107. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18108. var _this = this;
  18109. if (attachUp === void 0) { attachUp = true; }
  18110. if (attachDown === void 0) { attachDown = true; }
  18111. if (attachMove === void 0) { attachMove = true; }
  18112. this._initActionManager = function (act, clickInfo) {
  18113. if (!_this._meshPickProceed) {
  18114. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18115. _this._currentPickResult = pickResult;
  18116. if (pickResult) {
  18117. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18118. }
  18119. _this._meshPickProceed = true;
  18120. }
  18121. return act;
  18122. };
  18123. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18124. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18125. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18126. btn !== _this._previousButtonPressed) {
  18127. _this._doubleClickOccured = false;
  18128. clickInfo.singleClick = true;
  18129. clickInfo.ignore = false;
  18130. cb(clickInfo, _this._currentPickResult);
  18131. }
  18132. };
  18133. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18134. var clickInfo = new ClickInfo();
  18135. _this._currentPickResult = null;
  18136. var act = null;
  18137. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18138. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18139. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18140. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18141. act = _this._initActionManager(act, clickInfo);
  18142. if (act)
  18143. checkPicking = act.hasPickTriggers;
  18144. }
  18145. if (checkPicking) {
  18146. var btn = evt.button;
  18147. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18148. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18149. if (!clickInfo.hasSwiped) {
  18150. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18151. if (!checkSingleClickImmediately) {
  18152. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18153. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18154. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18155. act = _this._initActionManager(act, clickInfo);
  18156. if (act)
  18157. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18158. }
  18159. }
  18160. if (checkSingleClickImmediately) {
  18161. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18162. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18163. btn !== _this._previousButtonPressed) {
  18164. clickInfo.singleClick = true;
  18165. cb(clickInfo, _this._currentPickResult);
  18166. }
  18167. }
  18168. else {
  18169. // wait that no double click has been raised during the double click delay
  18170. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18171. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18172. }
  18173. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18174. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18175. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18176. act = _this._initActionManager(act, clickInfo);
  18177. if (act)
  18178. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18179. }
  18180. if (checkDoubleClick) {
  18181. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18182. if (btn === _this._previousButtonPressed &&
  18183. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18184. !_this._doubleClickOccured) {
  18185. // pointer has not moved for 2 clicks, it's a double click
  18186. if (!clickInfo.hasSwiped &&
  18187. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18188. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18189. _this._previousStartingPointerTime = 0;
  18190. _this._doubleClickOccured = true;
  18191. clickInfo.doubleClick = true;
  18192. clickInfo.ignore = false;
  18193. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18194. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18195. }
  18196. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18197. cb(clickInfo, _this._currentPickResult);
  18198. }
  18199. else {
  18200. _this._doubleClickOccured = false;
  18201. _this._previousStartingPointerTime = _this._startingPointerTime;
  18202. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18203. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18204. _this._previousButtonPressed = btn;
  18205. _this._previousHasSwiped = clickInfo.hasSwiped;
  18206. if (Scene.ExclusiveDoubleClickMode) {
  18207. if (_this._previousDelayedSimpleClickTimeout) {
  18208. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18209. }
  18210. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18211. cb(clickInfo, _this._previousPickResult);
  18212. }
  18213. else {
  18214. cb(clickInfo, _this._currentPickResult);
  18215. }
  18216. }
  18217. }
  18218. else {
  18219. _this._doubleClickOccured = false;
  18220. _this._previousStartingPointerTime = _this._startingPointerTime;
  18221. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18222. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18223. _this._previousButtonPressed = btn;
  18224. _this._previousHasSwiped = clickInfo.hasSwiped;
  18225. }
  18226. }
  18227. }
  18228. }
  18229. clickInfo.ignore = true;
  18230. cb(clickInfo, _this._currentPickResult);
  18231. };
  18232. this._spritePredicate = function (sprite) {
  18233. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18234. };
  18235. this._onPointerMove = function (evt) {
  18236. _this._updatePointerPosition(evt);
  18237. // PreObservable support
  18238. if (_this.onPrePointerObservable.hasObservers()) {
  18239. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18240. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18241. _this.onPrePointerObservable.notifyObservers(pi, type);
  18242. if (pi.skipOnPointerObservable) {
  18243. return;
  18244. }
  18245. }
  18246. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18247. return;
  18248. }
  18249. if (!_this.pointerMovePredicate) {
  18250. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18251. }
  18252. // Meshes
  18253. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18254. _this._processPointerMove(pickResult, evt);
  18255. };
  18256. this._onPointerDown = function (evt) {
  18257. _this._totalPointersPressed++;
  18258. _this._pickedDownMesh = null;
  18259. _this._meshPickProceed = false;
  18260. _this._updatePointerPosition(evt);
  18261. if (_this.preventDefaultOnPointerDown && canvas) {
  18262. evt.preventDefault();
  18263. canvas.focus();
  18264. }
  18265. // PreObservable support
  18266. if (_this.onPrePointerObservable.hasObservers()) {
  18267. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18268. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18269. _this.onPrePointerObservable.notifyObservers(pi, type);
  18270. if (pi.skipOnPointerObservable) {
  18271. return;
  18272. }
  18273. }
  18274. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18275. return;
  18276. }
  18277. _this._startingPointerPosition.x = _this._pointerX;
  18278. _this._startingPointerPosition.y = _this._pointerY;
  18279. _this._startingPointerTime = new Date().getTime();
  18280. if (!_this.pointerDownPredicate) {
  18281. _this.pointerDownPredicate = function (mesh) {
  18282. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18283. };
  18284. }
  18285. // Meshes
  18286. _this._pickedDownMesh = null;
  18287. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18288. _this._processPointerDown(pickResult, evt);
  18289. // Sprites
  18290. _this._pickedDownSprite = null;
  18291. if (_this.spriteManagers.length > 0) {
  18292. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18293. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18294. if (pickResult.pickedSprite.actionManager) {
  18295. _this._pickedDownSprite = pickResult.pickedSprite;
  18296. switch (evt.button) {
  18297. case 0:
  18298. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18299. break;
  18300. case 1:
  18301. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18302. break;
  18303. case 2:
  18304. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18305. break;
  18306. }
  18307. if (pickResult.pickedSprite.actionManager) {
  18308. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18309. }
  18310. }
  18311. }
  18312. }
  18313. };
  18314. this._onPointerUp = function (evt) {
  18315. if (_this._totalPointersPressed === 0) {
  18316. return; // So we need to test it the pointer down was pressed before.
  18317. }
  18318. _this._totalPointersPressed--;
  18319. _this._pickedUpMesh = null;
  18320. _this._meshPickProceed = false;
  18321. _this._updatePointerPosition(evt);
  18322. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18323. // PreObservable support
  18324. if (_this.onPrePointerObservable.hasObservers()) {
  18325. if (!clickInfo.ignore) {
  18326. if (!clickInfo.hasSwiped) {
  18327. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18328. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18329. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18330. _this.onPrePointerObservable.notifyObservers(pi, type);
  18331. if (pi.skipOnPointerObservable) {
  18332. return;
  18333. }
  18334. }
  18335. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18336. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18337. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18338. _this.onPrePointerObservable.notifyObservers(pi, type);
  18339. if (pi.skipOnPointerObservable) {
  18340. return;
  18341. }
  18342. }
  18343. }
  18344. }
  18345. else {
  18346. var type = BABYLON.PointerEventTypes.POINTERUP;
  18347. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18348. _this.onPrePointerObservable.notifyObservers(pi, type);
  18349. if (pi.skipOnPointerObservable) {
  18350. return;
  18351. }
  18352. }
  18353. }
  18354. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18355. return;
  18356. }
  18357. if (!_this.pointerUpPredicate) {
  18358. _this.pointerUpPredicate = function (mesh) {
  18359. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18360. };
  18361. }
  18362. // Meshes
  18363. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18364. _this._initActionManager(null, clickInfo);
  18365. }
  18366. if (!pickResult) {
  18367. pickResult = _this._currentPickResult;
  18368. }
  18369. _this._processPointerUp(pickResult, evt, clickInfo);
  18370. // Sprites
  18371. if (_this.spriteManagers.length > 0) {
  18372. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18373. if (spritePickResult) {
  18374. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18375. if (spritePickResult.pickedSprite.actionManager) {
  18376. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18377. if (spritePickResult.pickedSprite.actionManager) {
  18378. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18379. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18380. }
  18381. }
  18382. }
  18383. }
  18384. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18385. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18386. }
  18387. }
  18388. }
  18389. _this._previousPickResult = _this._currentPickResult;
  18390. });
  18391. };
  18392. this._onKeyDown = function (evt) {
  18393. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18394. if (_this.onPreKeyboardObservable.hasObservers()) {
  18395. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18396. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18397. if (pi.skipOnPointerObservable) {
  18398. return;
  18399. }
  18400. }
  18401. if (_this.onKeyboardObservable.hasObservers()) {
  18402. var pi = new BABYLON.KeyboardInfo(type, evt);
  18403. _this.onKeyboardObservable.notifyObservers(pi, type);
  18404. }
  18405. if (_this.actionManager) {
  18406. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18407. }
  18408. };
  18409. this._onKeyUp = function (evt) {
  18410. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18411. if (_this.onPreKeyboardObservable.hasObservers()) {
  18412. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18413. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18414. if (pi.skipOnPointerObservable) {
  18415. return;
  18416. }
  18417. }
  18418. if (_this.onKeyboardObservable.hasObservers()) {
  18419. var pi = new BABYLON.KeyboardInfo(type, evt);
  18420. _this.onKeyboardObservable.notifyObservers(pi, type);
  18421. }
  18422. if (_this.actionManager) {
  18423. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18424. }
  18425. };
  18426. var engine = this.getEngine();
  18427. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18428. if (!canvas) {
  18429. return;
  18430. }
  18431. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18432. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18433. });
  18434. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18435. if (!canvas) {
  18436. return;
  18437. }
  18438. canvas.removeEventListener("keydown", _this._onKeyDown);
  18439. canvas.removeEventListener("keyup", _this._onKeyUp);
  18440. });
  18441. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18442. var canvas = this._engine.getRenderingCanvas();
  18443. if (!canvas) {
  18444. return;
  18445. }
  18446. if (attachMove) {
  18447. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18448. // Wheel
  18449. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18450. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18451. }
  18452. if (attachDown) {
  18453. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18454. }
  18455. if (attachUp) {
  18456. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18457. }
  18458. canvas.tabIndex = 1;
  18459. };
  18460. Scene.prototype.detachControl = function () {
  18461. var engine = this.getEngine();
  18462. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18463. var canvas = engine.getRenderingCanvas();
  18464. if (!canvas) {
  18465. return;
  18466. }
  18467. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18468. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18469. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18470. if (this._onCanvasBlurObserver) {
  18471. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18472. }
  18473. if (this._onCanvasFocusObserver) {
  18474. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18475. }
  18476. // Wheel
  18477. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18478. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18479. // Keyboard
  18480. canvas.removeEventListener("keydown", this._onKeyDown);
  18481. canvas.removeEventListener("keyup", this._onKeyUp);
  18482. // Observables
  18483. this.onKeyboardObservable.clear();
  18484. this.onPreKeyboardObservable.clear();
  18485. this.onPointerObservable.clear();
  18486. this.onPrePointerObservable.clear();
  18487. };
  18488. // Ready
  18489. Scene.prototype.isReady = function () {
  18490. if (this._isDisposed) {
  18491. return false;
  18492. }
  18493. if (this._pendingData.length > 0) {
  18494. return false;
  18495. }
  18496. var index;
  18497. // Geometries
  18498. for (index = 0; index < this._geometries.length; index++) {
  18499. var geometry = this._geometries[index];
  18500. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18501. return false;
  18502. }
  18503. }
  18504. // Meshes
  18505. for (index = 0; index < this.meshes.length; index++) {
  18506. var mesh = this.meshes[index];
  18507. if (!mesh.isEnabled()) {
  18508. continue;
  18509. }
  18510. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18511. continue;
  18512. }
  18513. if (!mesh.isReady()) {
  18514. return false;
  18515. }
  18516. var mat = mesh.material;
  18517. if (mat) {
  18518. if (!mat.isReady(mesh)) {
  18519. return false;
  18520. }
  18521. }
  18522. }
  18523. return true;
  18524. };
  18525. Scene.prototype.resetCachedMaterial = function () {
  18526. this._cachedMaterial = null;
  18527. this._cachedEffect = null;
  18528. this._cachedVisibility = null;
  18529. };
  18530. Scene.prototype.registerBeforeRender = function (func) {
  18531. this.onBeforeRenderObservable.add(func);
  18532. };
  18533. Scene.prototype.unregisterBeforeRender = function (func) {
  18534. this.onBeforeRenderObservable.removeCallback(func);
  18535. };
  18536. Scene.prototype.registerAfterRender = function (func) {
  18537. this.onAfterRenderObservable.add(func);
  18538. };
  18539. Scene.prototype.unregisterAfterRender = function (func) {
  18540. this.onAfterRenderObservable.removeCallback(func);
  18541. };
  18542. Scene.prototype._addPendingData = function (data) {
  18543. this._pendingData.push(data);
  18544. };
  18545. Scene.prototype._removePendingData = function (data) {
  18546. var index = this._pendingData.indexOf(data);
  18547. if (index !== -1) {
  18548. this._pendingData.splice(index, 1);
  18549. }
  18550. };
  18551. Scene.prototype.getWaitingItemsCount = function () {
  18552. return this._pendingData.length;
  18553. };
  18554. /**
  18555. * Registers a function to be executed when the scene is ready.
  18556. * @param {Function} func - the function to be executed.
  18557. */
  18558. Scene.prototype.executeWhenReady = function (func) {
  18559. var _this = this;
  18560. this.onReadyObservable.add(func);
  18561. if (this._executeWhenReadyTimeoutId !== -1) {
  18562. return;
  18563. }
  18564. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18565. _this._checkIsReady();
  18566. }, 150);
  18567. };
  18568. Scene.prototype._checkIsReady = function () {
  18569. var _this = this;
  18570. if (this.isReady()) {
  18571. this.onReadyObservable.notifyObservers(this);
  18572. this.onReadyObservable.clear();
  18573. this._executeWhenReadyTimeoutId = -1;
  18574. return;
  18575. }
  18576. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18577. _this._checkIsReady();
  18578. }, 150);
  18579. };
  18580. // Animations
  18581. /**
  18582. * Will start the animation sequence of a given target
  18583. * @param target - the target
  18584. * @param {number} from - from which frame should animation start
  18585. * @param {number} to - till which frame should animation run.
  18586. * @param {boolean} [loop] - should the animation loop
  18587. * @param {number} [speedRatio] - the speed in which to run the animation
  18588. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18589. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18590. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18591. * See BABYLON.Animatable
  18592. */
  18593. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18594. if (speedRatio === void 0) { speedRatio = 1.0; }
  18595. if (from > to && speedRatio > 0) {
  18596. speedRatio *= -1;
  18597. }
  18598. this.stopAnimation(target);
  18599. if (!animatable) {
  18600. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18601. }
  18602. // Local animations
  18603. if (target.animations) {
  18604. animatable.appendAnimations(target, target.animations);
  18605. }
  18606. // Children animations
  18607. if (target.getAnimatables) {
  18608. var animatables = target.getAnimatables();
  18609. for (var index = 0; index < animatables.length; index++) {
  18610. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18611. }
  18612. }
  18613. animatable.reset();
  18614. return animatable;
  18615. };
  18616. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18617. if (speedRatio === undefined) {
  18618. speedRatio = 1.0;
  18619. }
  18620. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18621. return animatable;
  18622. };
  18623. Scene.prototype.getAnimatableByTarget = function (target) {
  18624. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18625. if (this._activeAnimatables[index].target === target) {
  18626. return this._activeAnimatables[index];
  18627. }
  18628. }
  18629. return null;
  18630. };
  18631. Object.defineProperty(Scene.prototype, "Animatables", {
  18632. get: function () {
  18633. return this._activeAnimatables;
  18634. },
  18635. enumerable: true,
  18636. configurable: true
  18637. });
  18638. /**
  18639. * Will stop the animation of the given target
  18640. * @param target - the target
  18641. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18642. * @see beginAnimation
  18643. */
  18644. Scene.prototype.stopAnimation = function (target, animationName) {
  18645. var animatable = this.getAnimatableByTarget(target);
  18646. if (animatable) {
  18647. animatable.stop(animationName);
  18648. }
  18649. };
  18650. Scene.prototype._animate = function () {
  18651. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18652. return;
  18653. }
  18654. // Getting time
  18655. var now = BABYLON.Tools.Now;
  18656. if (!this._animationTimeLast) {
  18657. if (this._pendingData.length > 0) {
  18658. return;
  18659. }
  18660. this._animationTimeLast = now;
  18661. }
  18662. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18663. this._animationTime += deltaTime;
  18664. this._animationTimeLast = now;
  18665. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18666. this._activeAnimatables[index]._animate(this._animationTime);
  18667. }
  18668. };
  18669. // Matrix
  18670. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18671. this._useAlternateCameraConfiguration = active;
  18672. };
  18673. Scene.prototype.getViewMatrix = function () {
  18674. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18675. };
  18676. Scene.prototype.getProjectionMatrix = function () {
  18677. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18678. };
  18679. Scene.prototype.getTransformMatrix = function () {
  18680. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18681. };
  18682. Scene.prototype.setTransformMatrix = function (view, projection) {
  18683. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18684. return;
  18685. }
  18686. this._viewUpdateFlag = view.updateFlag;
  18687. this._projectionUpdateFlag = projection.updateFlag;
  18688. this._viewMatrix = view;
  18689. this._projectionMatrix = projection;
  18690. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18691. // Update frustum
  18692. if (!this._frustumPlanes) {
  18693. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18694. }
  18695. else {
  18696. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18697. }
  18698. if (this.activeCamera && this.activeCamera._alternateCamera) {
  18699. var otherCamera = this.activeCamera._alternateCamera;
  18700. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18701. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18702. }
  18703. if (this._sceneUbo.useUbo) {
  18704. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18705. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18706. this._sceneUbo.update();
  18707. }
  18708. };
  18709. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18710. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18711. return;
  18712. }
  18713. this._alternateViewUpdateFlag = view.updateFlag;
  18714. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18715. this._alternateViewMatrix = view;
  18716. this._alternateProjectionMatrix = projection;
  18717. if (!this._alternateTransformMatrix) {
  18718. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18719. }
  18720. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18721. if (!this._alternateSceneUbo) {
  18722. this._createAlternateUbo();
  18723. }
  18724. if (this._alternateSceneUbo.useUbo) {
  18725. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18726. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18727. this._alternateSceneUbo.update();
  18728. }
  18729. };
  18730. Scene.prototype.getSceneUniformBuffer = function () {
  18731. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18732. };
  18733. // Methods
  18734. Scene.prototype.getUniqueId = function () {
  18735. var result = Scene._uniqueIdCounter;
  18736. Scene._uniqueIdCounter++;
  18737. return result;
  18738. };
  18739. Scene.prototype.addMesh = function (newMesh) {
  18740. this.meshes.push(newMesh);
  18741. //notify the collision coordinator
  18742. if (this.collisionCoordinator) {
  18743. this.collisionCoordinator.onMeshAdded(newMesh);
  18744. }
  18745. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18746. };
  18747. Scene.prototype.removeMesh = function (toRemove) {
  18748. var index = this.meshes.indexOf(toRemove);
  18749. if (index !== -1) {
  18750. // Remove from the scene if mesh found
  18751. this.meshes.splice(index, 1);
  18752. }
  18753. //notify the collision coordinator
  18754. if (this.collisionCoordinator) {
  18755. this.collisionCoordinator.onMeshRemoved(toRemove);
  18756. }
  18757. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18758. return index;
  18759. };
  18760. Scene.prototype.removeSkeleton = function (toRemove) {
  18761. var index = this.skeletons.indexOf(toRemove);
  18762. if (index !== -1) {
  18763. // Remove from the scene if found
  18764. this.skeletons.splice(index, 1);
  18765. }
  18766. return index;
  18767. };
  18768. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18769. var index = this.morphTargetManagers.indexOf(toRemove);
  18770. if (index !== -1) {
  18771. // Remove from the scene if found
  18772. this.morphTargetManagers.splice(index, 1);
  18773. }
  18774. return index;
  18775. };
  18776. Scene.prototype.removeLight = function (toRemove) {
  18777. var index = this.lights.indexOf(toRemove);
  18778. if (index !== -1) {
  18779. // Remove from the scene if mesh found
  18780. this.lights.splice(index, 1);
  18781. this.sortLightsByPriority();
  18782. }
  18783. this.onLightRemovedObservable.notifyObservers(toRemove);
  18784. return index;
  18785. };
  18786. Scene.prototype.removeCamera = function (toRemove) {
  18787. var index = this.cameras.indexOf(toRemove);
  18788. if (index !== -1) {
  18789. // Remove from the scene if mesh found
  18790. this.cameras.splice(index, 1);
  18791. }
  18792. // Remove from activeCameras
  18793. var index2 = this.activeCameras.indexOf(toRemove);
  18794. if (index2 !== -1) {
  18795. // Remove from the scene if mesh found
  18796. this.activeCameras.splice(index2, 1);
  18797. }
  18798. // Reset the activeCamera
  18799. if (this.activeCamera === toRemove) {
  18800. if (this.cameras.length > 0) {
  18801. this.activeCamera = this.cameras[0];
  18802. }
  18803. else {
  18804. this.activeCamera = null;
  18805. }
  18806. }
  18807. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18808. return index;
  18809. };
  18810. Scene.prototype.addLight = function (newLight) {
  18811. this.lights.push(newLight);
  18812. this.sortLightsByPriority();
  18813. this.onNewLightAddedObservable.notifyObservers(newLight);
  18814. };
  18815. Scene.prototype.sortLightsByPriority = function () {
  18816. if (this.requireLightSorting) {
  18817. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18818. }
  18819. };
  18820. Scene.prototype.addCamera = function (newCamera) {
  18821. this.cameras.push(newCamera);
  18822. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18823. };
  18824. /**
  18825. * Switch active camera
  18826. * @param {Camera} newCamera - new active camera
  18827. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18828. */
  18829. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18830. if (attachControl === void 0) { attachControl = true; }
  18831. var canvas = this._engine.getRenderingCanvas();
  18832. if (!canvas) {
  18833. return;
  18834. }
  18835. if (this.activeCamera) {
  18836. this.activeCamera.detachControl(canvas);
  18837. }
  18838. this.activeCamera = newCamera;
  18839. if (attachControl) {
  18840. newCamera.attachControl(canvas);
  18841. }
  18842. };
  18843. /**
  18844. * sets the active camera of the scene using its ID
  18845. * @param {string} id - the camera's ID
  18846. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18847. * @see activeCamera
  18848. */
  18849. Scene.prototype.setActiveCameraByID = function (id) {
  18850. var camera = this.getCameraByID(id);
  18851. if (camera) {
  18852. this.activeCamera = camera;
  18853. return camera;
  18854. }
  18855. return null;
  18856. };
  18857. /**
  18858. * sets the active camera of the scene using its name
  18859. * @param {string} name - the camera's name
  18860. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18861. * @see activeCamera
  18862. */
  18863. Scene.prototype.setActiveCameraByName = function (name) {
  18864. var camera = this.getCameraByName(name);
  18865. if (camera) {
  18866. this.activeCamera = camera;
  18867. return camera;
  18868. }
  18869. return null;
  18870. };
  18871. /**
  18872. * get a material using its id
  18873. * @param {string} the material's ID
  18874. * @return {BABYLON.Material|null} the material or null if none found.
  18875. */
  18876. Scene.prototype.getMaterialByID = function (id) {
  18877. for (var index = 0; index < this.materials.length; index++) {
  18878. if (this.materials[index].id === id) {
  18879. return this.materials[index];
  18880. }
  18881. }
  18882. return null;
  18883. };
  18884. /**
  18885. * get a material using its name
  18886. * @param {string} the material's name
  18887. * @return {BABYLON.Material|null} the material or null if none found.
  18888. */
  18889. Scene.prototype.getMaterialByName = function (name) {
  18890. for (var index = 0; index < this.materials.length; index++) {
  18891. if (this.materials[index].name === name) {
  18892. return this.materials[index];
  18893. }
  18894. }
  18895. return null;
  18896. };
  18897. Scene.prototype.getLensFlareSystemByName = function (name) {
  18898. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18899. if (this.lensFlareSystems[index].name === name) {
  18900. return this.lensFlareSystems[index];
  18901. }
  18902. }
  18903. return null;
  18904. };
  18905. Scene.prototype.getLensFlareSystemByID = function (id) {
  18906. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18907. if (this.lensFlareSystems[index].id === id) {
  18908. return this.lensFlareSystems[index];
  18909. }
  18910. }
  18911. return null;
  18912. };
  18913. Scene.prototype.getCameraByID = function (id) {
  18914. for (var index = 0; index < this.cameras.length; index++) {
  18915. if (this.cameras[index].id === id) {
  18916. return this.cameras[index];
  18917. }
  18918. }
  18919. return null;
  18920. };
  18921. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18922. for (var index = 0; index < this.cameras.length; index++) {
  18923. if (this.cameras[index].uniqueId === uniqueId) {
  18924. return this.cameras[index];
  18925. }
  18926. }
  18927. return null;
  18928. };
  18929. /**
  18930. * get a camera using its name
  18931. * @param {string} the camera's name
  18932. * @return {BABYLON.Camera|null} the camera or null if none found.
  18933. */
  18934. Scene.prototype.getCameraByName = function (name) {
  18935. for (var index = 0; index < this.cameras.length; index++) {
  18936. if (this.cameras[index].name === name) {
  18937. return this.cameras[index];
  18938. }
  18939. }
  18940. return null;
  18941. };
  18942. /**
  18943. * get a bone using its id
  18944. * @param {string} the bone's id
  18945. * @return {BABYLON.Bone|null} the bone or null if not found
  18946. */
  18947. Scene.prototype.getBoneByID = function (id) {
  18948. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18949. var skeleton = this.skeletons[skeletonIndex];
  18950. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18951. if (skeleton.bones[boneIndex].id === id) {
  18952. return skeleton.bones[boneIndex];
  18953. }
  18954. }
  18955. }
  18956. return null;
  18957. };
  18958. /**
  18959. * get a bone using its id
  18960. * @param {string} the bone's name
  18961. * @return {BABYLON.Bone|null} the bone or null if not found
  18962. */
  18963. Scene.prototype.getBoneByName = function (name) {
  18964. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18965. var skeleton = this.skeletons[skeletonIndex];
  18966. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18967. if (skeleton.bones[boneIndex].name === name) {
  18968. return skeleton.bones[boneIndex];
  18969. }
  18970. }
  18971. }
  18972. return null;
  18973. };
  18974. /**
  18975. * get a light node using its name
  18976. * @param {string} the light's name
  18977. * @return {BABYLON.Light|null} the light or null if none found.
  18978. */
  18979. Scene.prototype.getLightByName = function (name) {
  18980. for (var index = 0; index < this.lights.length; index++) {
  18981. if (this.lights[index].name === name) {
  18982. return this.lights[index];
  18983. }
  18984. }
  18985. return null;
  18986. };
  18987. /**
  18988. * get a light node using its ID
  18989. * @param {string} the light's id
  18990. * @return {BABYLON.Light|null} the light or null if none found.
  18991. */
  18992. Scene.prototype.getLightByID = function (id) {
  18993. for (var index = 0; index < this.lights.length; index++) {
  18994. if (this.lights[index].id === id) {
  18995. return this.lights[index];
  18996. }
  18997. }
  18998. return null;
  18999. };
  19000. /**
  19001. * get a light node using its scene-generated unique ID
  19002. * @param {number} the light's unique id
  19003. * @return {BABYLON.Light|null} the light or null if none found.
  19004. */
  19005. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19006. for (var index = 0; index < this.lights.length; index++) {
  19007. if (this.lights[index].uniqueId === uniqueId) {
  19008. return this.lights[index];
  19009. }
  19010. }
  19011. return null;
  19012. };
  19013. /**
  19014. * get a particle system by id
  19015. * @param id {number} the particle system id
  19016. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19017. */
  19018. Scene.prototype.getParticleSystemByID = function (id) {
  19019. for (var index = 0; index < this.particleSystems.length; index++) {
  19020. if (this.particleSystems[index].id === id) {
  19021. return this.particleSystems[index];
  19022. }
  19023. }
  19024. return null;
  19025. };
  19026. /**
  19027. * get a geometry using its ID
  19028. * @param {string} the geometry's id
  19029. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19030. */
  19031. Scene.prototype.getGeometryByID = function (id) {
  19032. for (var index = 0; index < this._geometries.length; index++) {
  19033. if (this._geometries[index].id === id) {
  19034. return this._geometries[index];
  19035. }
  19036. }
  19037. return null;
  19038. };
  19039. /**
  19040. * add a new geometry to this scene.
  19041. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19042. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19043. * @return {boolean} was the geometry added or not
  19044. */
  19045. Scene.prototype.pushGeometry = function (geometry, force) {
  19046. if (!force && this.getGeometryByID(geometry.id)) {
  19047. return false;
  19048. }
  19049. this._geometries.push(geometry);
  19050. //notify the collision coordinator
  19051. if (this.collisionCoordinator) {
  19052. this.collisionCoordinator.onGeometryAdded(geometry);
  19053. }
  19054. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19055. return true;
  19056. };
  19057. /**
  19058. * Removes an existing geometry
  19059. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19060. * @return {boolean} was the geometry removed or not
  19061. */
  19062. Scene.prototype.removeGeometry = function (geometry) {
  19063. var index = this._geometries.indexOf(geometry);
  19064. if (index > -1) {
  19065. this._geometries.splice(index, 1);
  19066. //notify the collision coordinator
  19067. if (this.collisionCoordinator) {
  19068. this.collisionCoordinator.onGeometryDeleted(geometry);
  19069. }
  19070. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19071. return true;
  19072. }
  19073. return false;
  19074. };
  19075. Scene.prototype.getGeometries = function () {
  19076. return this._geometries;
  19077. };
  19078. /**
  19079. * Get the first added mesh found of a given ID
  19080. * @param {string} id - the id to search for
  19081. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19082. */
  19083. Scene.prototype.getMeshByID = function (id) {
  19084. for (var index = 0; index < this.meshes.length; index++) {
  19085. if (this.meshes[index].id === id) {
  19086. return this.meshes[index];
  19087. }
  19088. }
  19089. return null;
  19090. };
  19091. Scene.prototype.getMeshesByID = function (id) {
  19092. return this.meshes.filter(function (m) {
  19093. return m.id === id;
  19094. });
  19095. };
  19096. /**
  19097. * Get a mesh with its auto-generated unique id
  19098. * @param {number} uniqueId - the unique id to search for
  19099. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19100. */
  19101. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19102. for (var index = 0; index < this.meshes.length; index++) {
  19103. if (this.meshes[index].uniqueId === uniqueId) {
  19104. return this.meshes[index];
  19105. }
  19106. }
  19107. return null;
  19108. };
  19109. /**
  19110. * Get a the last added mesh found of a given ID
  19111. * @param {string} id - the id to search for
  19112. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19113. */
  19114. Scene.prototype.getLastMeshByID = function (id) {
  19115. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19116. if (this.meshes[index].id === id) {
  19117. return this.meshes[index];
  19118. }
  19119. }
  19120. return null;
  19121. };
  19122. /**
  19123. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19124. * @param {string} id - the id to search for
  19125. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19126. */
  19127. Scene.prototype.getLastEntryByID = function (id) {
  19128. var index;
  19129. for (index = this.meshes.length - 1; index >= 0; index--) {
  19130. if (this.meshes[index].id === id) {
  19131. return this.meshes[index];
  19132. }
  19133. }
  19134. for (index = this.cameras.length - 1; index >= 0; index--) {
  19135. if (this.cameras[index].id === id) {
  19136. return this.cameras[index];
  19137. }
  19138. }
  19139. for (index = this.lights.length - 1; index >= 0; index--) {
  19140. if (this.lights[index].id === id) {
  19141. return this.lights[index];
  19142. }
  19143. }
  19144. return null;
  19145. };
  19146. Scene.prototype.getNodeByID = function (id) {
  19147. var mesh = this.getMeshByID(id);
  19148. if (mesh) {
  19149. return mesh;
  19150. }
  19151. var light = this.getLightByID(id);
  19152. if (light) {
  19153. return light;
  19154. }
  19155. var camera = this.getCameraByID(id);
  19156. if (camera) {
  19157. return camera;
  19158. }
  19159. var bone = this.getBoneByID(id);
  19160. return bone;
  19161. };
  19162. Scene.prototype.getNodeByName = function (name) {
  19163. var mesh = this.getMeshByName(name);
  19164. if (mesh) {
  19165. return mesh;
  19166. }
  19167. var light = this.getLightByName(name);
  19168. if (light) {
  19169. return light;
  19170. }
  19171. var camera = this.getCameraByName(name);
  19172. if (camera) {
  19173. return camera;
  19174. }
  19175. var bone = this.getBoneByName(name);
  19176. return bone;
  19177. };
  19178. Scene.prototype.getMeshByName = function (name) {
  19179. for (var index = 0; index < this.meshes.length; index++) {
  19180. if (this.meshes[index].name === name) {
  19181. return this.meshes[index];
  19182. }
  19183. }
  19184. return null;
  19185. };
  19186. Scene.prototype.getSoundByName = function (name) {
  19187. var index;
  19188. if (BABYLON.AudioEngine) {
  19189. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19190. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19191. return this.mainSoundTrack.soundCollection[index];
  19192. }
  19193. }
  19194. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19195. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19196. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19197. return this.soundTracks[sdIndex].soundCollection[index];
  19198. }
  19199. }
  19200. }
  19201. }
  19202. return null;
  19203. };
  19204. Scene.prototype.getLastSkeletonByID = function (id) {
  19205. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19206. if (this.skeletons[index].id === id) {
  19207. return this.skeletons[index];
  19208. }
  19209. }
  19210. return null;
  19211. };
  19212. Scene.prototype.getSkeletonById = function (id) {
  19213. for (var index = 0; index < this.skeletons.length; index++) {
  19214. if (this.skeletons[index].id === id) {
  19215. return this.skeletons[index];
  19216. }
  19217. }
  19218. return null;
  19219. };
  19220. Scene.prototype.getSkeletonByName = function (name) {
  19221. for (var index = 0; index < this.skeletons.length; index++) {
  19222. if (this.skeletons[index].name === name) {
  19223. return this.skeletons[index];
  19224. }
  19225. }
  19226. return null;
  19227. };
  19228. Scene.prototype.getMorphTargetManagerById = function (id) {
  19229. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19230. if (this.morphTargetManagers[index].uniqueId === id) {
  19231. return this.morphTargetManagers[index];
  19232. }
  19233. }
  19234. return null;
  19235. };
  19236. Scene.prototype.isActiveMesh = function (mesh) {
  19237. return (this._activeMeshes.indexOf(mesh) !== -1);
  19238. };
  19239. /**
  19240. * Return a the first highlight layer of the scene with a given name.
  19241. * @param name The name of the highlight layer to look for.
  19242. * @return The highlight layer if found otherwise null.
  19243. */
  19244. Scene.prototype.getHighlightLayerByName = function (name) {
  19245. for (var index = 0; index < this.highlightLayers.length; index++) {
  19246. if (this.highlightLayers[index].name === name) {
  19247. return this.highlightLayers[index];
  19248. }
  19249. }
  19250. return null;
  19251. };
  19252. Object.defineProperty(Scene.prototype, "uid", {
  19253. /**
  19254. * Return a unique id as a string which can serve as an identifier for the scene
  19255. */
  19256. get: function () {
  19257. if (!this._uid) {
  19258. this._uid = BABYLON.Tools.RandomId();
  19259. }
  19260. return this._uid;
  19261. },
  19262. enumerable: true,
  19263. configurable: true
  19264. });
  19265. /**
  19266. * Add an externaly attached data from its key.
  19267. * This method call will fail and return false, if such key already exists.
  19268. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19269. * @param key the unique key that identifies the data
  19270. * @param data the data object to associate to the key for this Engine instance
  19271. * @return true if no such key were already present and the data was added successfully, false otherwise
  19272. */
  19273. Scene.prototype.addExternalData = function (key, data) {
  19274. if (!this._externalData) {
  19275. this._externalData = new BABYLON.StringDictionary();
  19276. }
  19277. return this._externalData.add(key, data);
  19278. };
  19279. /**
  19280. * Get an externaly attached data from its key
  19281. * @param key the unique key that identifies the data
  19282. * @return the associated data, if present (can be null), or undefined if not present
  19283. */
  19284. Scene.prototype.getExternalData = function (key) {
  19285. if (!this._externalData) {
  19286. return null;
  19287. }
  19288. return this._externalData.get(key);
  19289. };
  19290. /**
  19291. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19292. * @param key the unique key that identifies the data
  19293. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19294. * @return the associated data, can be null if the factory returned null.
  19295. */
  19296. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19297. if (!this._externalData) {
  19298. this._externalData = new BABYLON.StringDictionary();
  19299. }
  19300. return this._externalData.getOrAddWithFactory(key, factory);
  19301. };
  19302. /**
  19303. * Remove an externaly attached data from the Engine instance
  19304. * @param key the unique key that identifies the data
  19305. * @return true if the data was successfully removed, false if it doesn't exist
  19306. */
  19307. Scene.prototype.removeExternalData = function (key) {
  19308. return this._externalData.remove(key);
  19309. };
  19310. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19311. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19312. var material = subMesh.getMaterial();
  19313. if (mesh.showSubMeshesBoundingBox) {
  19314. var boundingInfo = subMesh.getBoundingInfo();
  19315. if (boundingInfo) {
  19316. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19317. }
  19318. }
  19319. if (material) {
  19320. // Render targets
  19321. if (material.getRenderTargetTextures) {
  19322. if (this._processedMaterials.indexOf(material) === -1) {
  19323. this._processedMaterials.push(material);
  19324. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19325. }
  19326. }
  19327. // Dispatch
  19328. this._activeIndices.addCount(subMesh.indexCount, false);
  19329. this._renderingManager.dispatch(subMesh);
  19330. }
  19331. }
  19332. };
  19333. Scene.prototype._isInIntermediateRendering = function () {
  19334. return this._intermediateRendering;
  19335. };
  19336. /**
  19337. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19338. */
  19339. Scene.prototype.freezeActiveMeshes = function () {
  19340. this._evaluateActiveMeshes();
  19341. this._activeMeshesFrozen = true;
  19342. return this;
  19343. };
  19344. /**
  19345. * Use this function to restart evaluating active meshes on every frame
  19346. */
  19347. Scene.prototype.unfreezeActiveMeshes = function () {
  19348. this._activeMeshesFrozen = false;
  19349. return this;
  19350. };
  19351. Scene.prototype._evaluateActiveMeshes = function () {
  19352. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19353. return;
  19354. }
  19355. if (!this.activeCamera) {
  19356. return;
  19357. }
  19358. this.activeCamera._activeMeshes.reset();
  19359. this._activeMeshes.reset();
  19360. this._renderingManager.reset();
  19361. this._processedMaterials.reset();
  19362. this._activeParticleSystems.reset();
  19363. this._activeSkeletons.reset();
  19364. this._softwareSkinnedMeshes.reset();
  19365. if (this._boundingBoxRenderer) {
  19366. this._boundingBoxRenderer.reset();
  19367. }
  19368. // Meshes
  19369. var meshes;
  19370. var len;
  19371. if (this._selectionOctree) {
  19372. var selection = this._selectionOctree.select(this._frustumPlanes);
  19373. meshes = selection.data;
  19374. len = selection.length;
  19375. }
  19376. else {
  19377. len = this.meshes.length;
  19378. meshes = this.meshes;
  19379. }
  19380. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19381. var mesh = meshes[meshIndex];
  19382. if (mesh.isBlocked) {
  19383. continue;
  19384. }
  19385. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19386. if (!mesh.isReady() || !mesh.isEnabled()) {
  19387. continue;
  19388. }
  19389. mesh.computeWorldMatrix();
  19390. // Intersections
  19391. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19392. this._meshesForIntersections.pushNoDuplicate(mesh);
  19393. }
  19394. // Switch to current LOD
  19395. var meshLOD = mesh.getLOD(this.activeCamera);
  19396. if (!meshLOD) {
  19397. continue;
  19398. }
  19399. mesh._preActivate();
  19400. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19401. this._activeMeshes.push(mesh);
  19402. this.activeCamera._activeMeshes.push(mesh);
  19403. mesh._activate(this._renderId);
  19404. if (meshLOD !== mesh) {
  19405. meshLOD._activate(this._renderId);
  19406. }
  19407. this._activeMesh(mesh, meshLOD);
  19408. }
  19409. }
  19410. // Particle systems
  19411. this._particlesDuration.beginMonitoring();
  19412. if (this.particlesEnabled) {
  19413. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  19414. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19415. var particleSystem = this.particleSystems[particleIndex];
  19416. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19417. continue;
  19418. }
  19419. var emitter = particleSystem.emitter;
  19420. if (!emitter.position || emitter.isEnabled()) {
  19421. this._activeParticleSystems.push(particleSystem);
  19422. particleSystem.animate();
  19423. this._renderingManager.dispatchParticles(particleSystem);
  19424. }
  19425. }
  19426. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  19427. }
  19428. this._particlesDuration.endMonitoring(false);
  19429. };
  19430. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19431. if (mesh.skeleton && this.skeletonsEnabled) {
  19432. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19433. mesh.skeleton.prepare();
  19434. }
  19435. if (!mesh.computeBonesUsingShaders) {
  19436. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19437. }
  19438. }
  19439. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19440. var boundingInfo = sourceMesh.getBoundingInfo();
  19441. if (boundingInfo) {
  19442. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19443. }
  19444. }
  19445. if (mesh && mesh.subMeshes) {
  19446. // Submeshes Octrees
  19447. var len;
  19448. var subMeshes;
  19449. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19450. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19451. len = intersections.length;
  19452. subMeshes = intersections.data;
  19453. }
  19454. else {
  19455. subMeshes = mesh.subMeshes;
  19456. len = subMeshes.length;
  19457. }
  19458. for (var subIndex = 0; subIndex < len; subIndex++) {
  19459. var subMesh = subMeshes[subIndex];
  19460. this._evaluateSubMesh(subMesh, mesh);
  19461. }
  19462. }
  19463. };
  19464. Scene.prototype.updateTransformMatrix = function (force) {
  19465. if (!this.activeCamera) {
  19466. return;
  19467. }
  19468. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19469. };
  19470. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19471. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19472. };
  19473. Scene.prototype._renderForCamera = function (camera) {
  19474. if (camera && camera._skipRendering) {
  19475. return;
  19476. }
  19477. var engine = this._engine;
  19478. this.activeCamera = camera;
  19479. if (!this.activeCamera)
  19480. throw new Error("Active camera not set");
  19481. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19482. // Viewport
  19483. engine.setViewport(this.activeCamera.viewport);
  19484. // Camera
  19485. this.resetCachedMaterial();
  19486. this._renderId++;
  19487. this.activeCamera.update();
  19488. this.updateTransformMatrix();
  19489. if (camera._alternateCamera) {
  19490. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19491. this._alternateRendering = true;
  19492. }
  19493. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19494. // Meshes
  19495. this._evaluateActiveMeshesDuration.beginMonitoring();
  19496. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  19497. this._evaluateActiveMeshes();
  19498. this._evaluateActiveMeshesDuration.endMonitoring(false);
  19499. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  19500. // Software skinning
  19501. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19502. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19503. mesh.applySkeleton(mesh.skeleton);
  19504. }
  19505. // Render targets
  19506. this._renderTargetsDuration.beginMonitoring();
  19507. var needsRestoreFrameBuffer = false;
  19508. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19509. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19510. }
  19511. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19512. this._intermediateRendering = true;
  19513. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19514. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19515. var renderTarget = this._renderTargets.data[renderIndex];
  19516. if (renderTarget._shouldRender()) {
  19517. this._renderId++;
  19518. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19519. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19520. }
  19521. }
  19522. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19523. this._intermediateRendering = false;
  19524. this._renderId++;
  19525. needsRestoreFrameBuffer = true; // Restore back buffer
  19526. }
  19527. // Render HighlightLayer Texture
  19528. var stencilState = this._engine.getStencilBuffer();
  19529. var renderhighlights = false;
  19530. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19531. this._intermediateRendering = true;
  19532. for (var i = 0; i < this.highlightLayers.length; i++) {
  19533. var highlightLayer = this.highlightLayers[i];
  19534. if (highlightLayer.shouldRender() &&
  19535. (!highlightLayer.camera ||
  19536. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19537. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19538. renderhighlights = true;
  19539. var renderTarget = highlightLayer._mainTexture;
  19540. if (renderTarget._shouldRender()) {
  19541. this._renderId++;
  19542. renderTarget.render(false, false);
  19543. needsRestoreFrameBuffer = true;
  19544. }
  19545. }
  19546. }
  19547. this._intermediateRendering = false;
  19548. this._renderId++;
  19549. }
  19550. if (needsRestoreFrameBuffer) {
  19551. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19552. }
  19553. this._renderTargetsDuration.endMonitoring(false);
  19554. // Prepare Frame
  19555. this.postProcessManager._prepareFrame();
  19556. this._renderDuration.beginMonitoring();
  19557. // Backgrounds
  19558. var layerIndex;
  19559. var layer;
  19560. if (this.layers.length) {
  19561. engine.setDepthBuffer(false);
  19562. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19563. layer = this.layers[layerIndex];
  19564. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19565. layer.render();
  19566. }
  19567. }
  19568. engine.setDepthBuffer(true);
  19569. }
  19570. // Render
  19571. BABYLON.Tools.StartPerformanceCounter("Main render");
  19572. // Activate HighlightLayer stencil
  19573. if (renderhighlights) {
  19574. this._engine.setStencilBuffer(true);
  19575. }
  19576. this._renderingManager.render(null, null, true, true);
  19577. // Restore HighlightLayer stencil
  19578. if (renderhighlights) {
  19579. this._engine.setStencilBuffer(stencilState);
  19580. }
  19581. BABYLON.Tools.EndPerformanceCounter("Main render");
  19582. // Bounding boxes
  19583. if (this._boundingBoxRenderer) {
  19584. this._boundingBoxRenderer.render();
  19585. }
  19586. // Lens flares
  19587. if (this.lensFlaresEnabled) {
  19588. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19589. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19590. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19591. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19592. lensFlareSystem.render();
  19593. }
  19594. }
  19595. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19596. }
  19597. // Foregrounds
  19598. if (this.layers.length) {
  19599. engine.setDepthBuffer(false);
  19600. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19601. layer = this.layers[layerIndex];
  19602. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19603. layer.render();
  19604. }
  19605. }
  19606. engine.setDepthBuffer(true);
  19607. }
  19608. // Highlight Layer
  19609. if (renderhighlights) {
  19610. engine.setDepthBuffer(false);
  19611. for (var i = 0; i < this.highlightLayers.length; i++) {
  19612. if (this.highlightLayers[i].shouldRender()) {
  19613. this.highlightLayers[i].render();
  19614. }
  19615. }
  19616. engine.setDepthBuffer(true);
  19617. }
  19618. this._renderDuration.endMonitoring(false);
  19619. // Finalize frame
  19620. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19621. // Reset some special arrays
  19622. this._renderTargets.reset();
  19623. this._alternateRendering = false;
  19624. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19625. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19626. };
  19627. Scene.prototype._processSubCameras = function (camera) {
  19628. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19629. this._renderForCamera(camera);
  19630. return;
  19631. }
  19632. // Update camera
  19633. if (this.activeCamera) {
  19634. this.activeCamera.update();
  19635. }
  19636. // rig cameras
  19637. for (var index = 0; index < camera._rigCameras.length; index++) {
  19638. this._renderForCamera(camera._rigCameras[index]);
  19639. }
  19640. this.activeCamera = camera;
  19641. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19642. };
  19643. Scene.prototype._checkIntersections = function () {
  19644. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19645. var sourceMesh = this._meshesForIntersections.data[index];
  19646. if (!sourceMesh.actionManager) {
  19647. continue;
  19648. }
  19649. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19650. var action = sourceMesh.actionManager.actions[actionIndex];
  19651. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19652. var parameters = action.getTriggerParameter();
  19653. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19654. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19655. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19656. if (areIntersecting && currentIntersectionInProgress === -1) {
  19657. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19658. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19659. sourceMesh._intersectionsInProgress.push(otherMesh);
  19660. }
  19661. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19662. sourceMesh._intersectionsInProgress.push(otherMesh);
  19663. }
  19664. }
  19665. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19666. //They intersected, and now they don't.
  19667. //is this trigger an exit trigger? execute an event.
  19668. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19669. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19670. }
  19671. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19672. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19673. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19674. }
  19675. }
  19676. }
  19677. }
  19678. }
  19679. };
  19680. Scene.prototype.render = function () {
  19681. if (this.isDisposed) {
  19682. return;
  19683. }
  19684. this._interFrameDuration.endMonitoring();
  19685. this._lastFrameDuration.beginMonitoring();
  19686. this._particlesDuration.fetchNewFrame();
  19687. this._spritesDuration.fetchNewFrame();
  19688. this._activeParticles.fetchNewFrame();
  19689. this._renderDuration.fetchNewFrame();
  19690. this._renderTargetsDuration.fetchNewFrame();
  19691. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19692. this._totalVertices.fetchNewFrame();
  19693. this._activeIndices.fetchNewFrame();
  19694. this._activeBones.fetchNewFrame();
  19695. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19696. this._meshesForIntersections.reset();
  19697. this.resetCachedMaterial();
  19698. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19699. // Actions
  19700. if (this.actionManager) {
  19701. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  19702. }
  19703. //Simplification Queue
  19704. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19705. this.simplificationQueue.executeNext();
  19706. }
  19707. if (this._engine.isDeterministicLockStep()) {
  19708. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19709. var defaultTimeStep = (60.0 / 1000.0);
  19710. if (this._physicsEngine) {
  19711. defaultTimeStep = this._physicsEngine.getTimeStep();
  19712. }
  19713. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19714. this._timeAccumulator += deltaTime;
  19715. // compute the amount of fixed steps we should have taken since the last step
  19716. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19717. internalSteps = Math.min(internalSteps, maxSubSteps);
  19718. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19719. this.onBeforeStepObservable.notifyObservers(this);
  19720. // Animations
  19721. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19722. this._animate();
  19723. // Physics
  19724. if (this._physicsEngine) {
  19725. BABYLON.Tools.StartPerformanceCounter("Physics");
  19726. this._physicsEngine._step(defaultTimeStep);
  19727. BABYLON.Tools.EndPerformanceCounter("Physics");
  19728. }
  19729. this._timeAccumulator -= defaultTimeStep;
  19730. this.onAfterStepObservable.notifyObservers(this);
  19731. this._currentStepId++;
  19732. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19733. this._evaluateActiveMeshes();
  19734. }
  19735. }
  19736. }
  19737. else {
  19738. // Animations
  19739. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19740. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19741. this._animate();
  19742. // Physics
  19743. if (this._physicsEngine) {
  19744. BABYLON.Tools.StartPerformanceCounter("Physics");
  19745. this._physicsEngine._step(deltaTime / 1000.0);
  19746. BABYLON.Tools.EndPerformanceCounter("Physics");
  19747. }
  19748. }
  19749. // Before render
  19750. this.onBeforeRenderObservable.notifyObservers(this);
  19751. // Customs render targets
  19752. this._renderTargetsDuration.beginMonitoring();
  19753. var engine = this.getEngine();
  19754. var currentActiveCamera = this.activeCamera;
  19755. if (this.renderTargetsEnabled) {
  19756. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19757. this._intermediateRendering = true;
  19758. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19759. var renderTarget = this.customRenderTargets[customIndex];
  19760. if (renderTarget._shouldRender()) {
  19761. this._renderId++;
  19762. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19763. if (!this.activeCamera)
  19764. throw new Error("Active camera not set");
  19765. // Viewport
  19766. engine.setViewport(this.activeCamera.viewport);
  19767. // Camera
  19768. this.updateTransformMatrix();
  19769. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19770. }
  19771. }
  19772. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19773. this._intermediateRendering = false;
  19774. this._renderId++;
  19775. }
  19776. // Restore back buffer
  19777. if (this.customRenderTargets.length > 0) {
  19778. engine.restoreDefaultFramebuffer();
  19779. }
  19780. this._renderTargetsDuration.endMonitoring();
  19781. this.activeCamera = currentActiveCamera;
  19782. // Procedural textures
  19783. if (this.proceduralTexturesEnabled) {
  19784. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19785. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19786. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19787. if (proceduralTexture._shouldRender()) {
  19788. proceduralTexture.render();
  19789. }
  19790. }
  19791. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19792. }
  19793. // Clear
  19794. if (this.autoClearDepthAndStencil || this.autoClear) {
  19795. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19796. }
  19797. // Shadows
  19798. if (this.shadowsEnabled) {
  19799. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19800. var light = this.lights[lightIndex];
  19801. var shadowGenerator = light.getShadowGenerator();
  19802. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19803. var shadowMap = (shadowGenerator.getShadowMap());
  19804. if (this.textures.indexOf(shadowMap) !== -1) {
  19805. this._renderTargets.push(shadowMap);
  19806. }
  19807. }
  19808. }
  19809. }
  19810. // Depth renderer
  19811. if (this._depthRenderer) {
  19812. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19813. }
  19814. // Geometry renderer
  19815. if (this._geometryBufferRenderer) {
  19816. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19817. }
  19818. // RenderPipeline
  19819. if (this._postProcessRenderPipelineManager) {
  19820. this._postProcessRenderPipelineManager.update();
  19821. }
  19822. // Multi-cameras?
  19823. if (this.activeCameras.length > 0) {
  19824. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19825. if (cameraIndex > 0) {
  19826. this._engine.clear(null, false, true, true);
  19827. }
  19828. this._processSubCameras(this.activeCameras[cameraIndex]);
  19829. }
  19830. }
  19831. else {
  19832. if (!this.activeCamera) {
  19833. throw new Error("No camera defined");
  19834. }
  19835. this._processSubCameras(this.activeCamera);
  19836. }
  19837. // Intersection checks
  19838. this._checkIntersections();
  19839. // Update the audio listener attached to the camera
  19840. if (BABYLON.AudioEngine) {
  19841. this._updateAudioParameters();
  19842. }
  19843. // After render
  19844. if (this.afterRender) {
  19845. this.afterRender();
  19846. }
  19847. this.onAfterRenderObservable.notifyObservers(this);
  19848. // Cleaning
  19849. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19850. var data = this._toBeDisposed.data[index];
  19851. if (data) {
  19852. data.dispose();
  19853. }
  19854. this._toBeDisposed[index] = null;
  19855. }
  19856. this._toBeDisposed.reset();
  19857. if (this.dumpNextRenderTargets) {
  19858. this.dumpNextRenderTargets = false;
  19859. }
  19860. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19861. this._interFrameDuration.beginMonitoring();
  19862. this._lastFrameDuration.endMonitoring();
  19863. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19864. this._totalLightsCounter.addCount(this.lights.length, true);
  19865. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19866. this._totalTexturesCounter.addCount(this.textures.length, true);
  19867. this._activeBones.addCount(0, true);
  19868. this._activeIndices.addCount(0, true);
  19869. this._activeParticles.addCount(0, true);
  19870. };
  19871. Scene.prototype._updateAudioParameters = function () {
  19872. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19873. return;
  19874. }
  19875. var listeningCamera;
  19876. var audioEngine = BABYLON.Engine.audioEngine;
  19877. if (this.activeCameras.length > 0) {
  19878. listeningCamera = this.activeCameras[0];
  19879. }
  19880. else {
  19881. listeningCamera = this.activeCamera;
  19882. }
  19883. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  19884. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19885. // for VR cameras
  19886. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19887. listeningCamera = listeningCamera.rigCameras[0];
  19888. }
  19889. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19890. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19891. cameraDirection.normalize();
  19892. // To avoid some errors on GearVR
  19893. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19894. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19895. }
  19896. var i;
  19897. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19898. var sound = this.mainSoundTrack.soundCollection[i];
  19899. if (sound.useCustomAttenuation) {
  19900. sound.updateDistanceFromListener();
  19901. }
  19902. }
  19903. for (i = 0; i < this.soundTracks.length; i++) {
  19904. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19905. sound = this.soundTracks[i].soundCollection[j];
  19906. if (sound.useCustomAttenuation) {
  19907. sound.updateDistanceFromListener();
  19908. }
  19909. }
  19910. }
  19911. }
  19912. };
  19913. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19914. // Audio
  19915. get: function () {
  19916. return this._audioEnabled;
  19917. },
  19918. set: function (value) {
  19919. this._audioEnabled = value;
  19920. if (BABYLON.AudioEngine) {
  19921. if (this._audioEnabled) {
  19922. this._enableAudio();
  19923. }
  19924. else {
  19925. this._disableAudio();
  19926. }
  19927. }
  19928. },
  19929. enumerable: true,
  19930. configurable: true
  19931. });
  19932. Scene.prototype._disableAudio = function () {
  19933. var i;
  19934. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19935. this.mainSoundTrack.soundCollection[i].pause();
  19936. }
  19937. for (i = 0; i < this.soundTracks.length; i++) {
  19938. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19939. this.soundTracks[i].soundCollection[j].pause();
  19940. }
  19941. }
  19942. };
  19943. Scene.prototype._enableAudio = function () {
  19944. var i;
  19945. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19946. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19947. this.mainSoundTrack.soundCollection[i].play();
  19948. }
  19949. }
  19950. for (i = 0; i < this.soundTracks.length; i++) {
  19951. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19952. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19953. this.soundTracks[i].soundCollection[j].play();
  19954. }
  19955. }
  19956. }
  19957. };
  19958. Object.defineProperty(Scene.prototype, "headphone", {
  19959. get: function () {
  19960. return this._headphone;
  19961. },
  19962. set: function (value) {
  19963. this._headphone = value;
  19964. if (BABYLON.AudioEngine) {
  19965. if (this._headphone) {
  19966. this._switchAudioModeForHeadphones();
  19967. }
  19968. else {
  19969. this._switchAudioModeForNormalSpeakers();
  19970. }
  19971. }
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Scene.prototype._switchAudioModeForHeadphones = function () {
  19977. this.mainSoundTrack.switchPanningModelToHRTF();
  19978. for (var i = 0; i < this.soundTracks.length; i++) {
  19979. this.soundTracks[i].switchPanningModelToHRTF();
  19980. }
  19981. };
  19982. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19983. this.mainSoundTrack.switchPanningModelToEqualPower();
  19984. for (var i = 0; i < this.soundTracks.length; i++) {
  19985. this.soundTracks[i].switchPanningModelToEqualPower();
  19986. }
  19987. };
  19988. Scene.prototype.enableDepthRenderer = function () {
  19989. if (this._depthRenderer) {
  19990. return this._depthRenderer;
  19991. }
  19992. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19993. return this._depthRenderer;
  19994. };
  19995. Scene.prototype.disableDepthRenderer = function () {
  19996. if (!this._depthRenderer) {
  19997. return;
  19998. }
  19999. this._depthRenderer.dispose();
  20000. this._depthRenderer = null;
  20001. };
  20002. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20003. if (ratio === void 0) { ratio = 1; }
  20004. if (this._geometryBufferRenderer) {
  20005. return this._geometryBufferRenderer;
  20006. }
  20007. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20008. if (!this._geometryBufferRenderer.isSupported) {
  20009. this._geometryBufferRenderer = null;
  20010. }
  20011. return this._geometryBufferRenderer;
  20012. };
  20013. Scene.prototype.disableGeometryBufferRenderer = function () {
  20014. if (!this._geometryBufferRenderer) {
  20015. return;
  20016. }
  20017. this._geometryBufferRenderer.dispose();
  20018. this._geometryBufferRenderer = null;
  20019. };
  20020. Scene.prototype.freezeMaterials = function () {
  20021. for (var i = 0; i < this.materials.length; i++) {
  20022. this.materials[i].freeze();
  20023. }
  20024. };
  20025. Scene.prototype.unfreezeMaterials = function () {
  20026. for (var i = 0; i < this.materials.length; i++) {
  20027. this.materials[i].unfreeze();
  20028. }
  20029. };
  20030. Scene.prototype.dispose = function () {
  20031. this.beforeRender = null;
  20032. this.afterRender = null;
  20033. this.skeletons = [];
  20034. this.morphTargetManagers = [];
  20035. this.importedMeshesFiles = new Array();
  20036. this.resetCachedMaterial();
  20037. if (this._depthRenderer) {
  20038. this._depthRenderer.dispose();
  20039. }
  20040. if (this._gamepadManager) {
  20041. this._gamepadManager.dispose();
  20042. this._gamepadManager = null;
  20043. }
  20044. // Smart arrays
  20045. if (this.activeCamera) {
  20046. this.activeCamera._activeMeshes.dispose();
  20047. this.activeCamera = null;
  20048. }
  20049. this._activeMeshes.dispose();
  20050. this._renderingManager.dispose();
  20051. this._processedMaterials.dispose();
  20052. this._activeParticleSystems.dispose();
  20053. this._activeSkeletons.dispose();
  20054. this._softwareSkinnedMeshes.dispose();
  20055. this._renderTargets.dispose();
  20056. if (this._boundingBoxRenderer) {
  20057. this._boundingBoxRenderer.dispose();
  20058. }
  20059. this._meshesForIntersections.dispose();
  20060. this._toBeDisposed.dispose();
  20061. // Debug layer
  20062. if (this._debugLayer) {
  20063. this._debugLayer.hide();
  20064. }
  20065. // Events
  20066. this.onDisposeObservable.notifyObservers(this);
  20067. this.onDisposeObservable.clear();
  20068. this.onBeforeRenderObservable.clear();
  20069. this.onAfterRenderObservable.clear();
  20070. this.detachControl();
  20071. // Release sounds & sounds tracks
  20072. if (BABYLON.AudioEngine) {
  20073. this.disposeSounds();
  20074. }
  20075. // VR Helper
  20076. if (this.VRHelper) {
  20077. this.VRHelper.dispose();
  20078. }
  20079. // Detach cameras
  20080. var canvas = this._engine.getRenderingCanvas();
  20081. if (canvas) {
  20082. var index;
  20083. for (index = 0; index < this.cameras.length; index++) {
  20084. this.cameras[index].detachControl(canvas);
  20085. }
  20086. }
  20087. // Release lights
  20088. while (this.lights.length) {
  20089. this.lights[0].dispose();
  20090. }
  20091. // Release meshes
  20092. while (this.meshes.length) {
  20093. this.meshes[0].dispose(true);
  20094. }
  20095. // Release cameras
  20096. while (this.cameras.length) {
  20097. this.cameras[0].dispose();
  20098. }
  20099. // Release materials
  20100. if (this.defaultMaterial) {
  20101. this.defaultMaterial.dispose();
  20102. }
  20103. while (this.multiMaterials.length) {
  20104. this.multiMaterials[0].dispose();
  20105. }
  20106. while (this.materials.length) {
  20107. this.materials[0].dispose();
  20108. }
  20109. // Release particles
  20110. while (this.particleSystems.length) {
  20111. this.particleSystems[0].dispose();
  20112. }
  20113. // Release sprites
  20114. while (this.spriteManagers.length) {
  20115. this.spriteManagers[0].dispose();
  20116. }
  20117. // Release postProcesses
  20118. while (this.postProcesses.length) {
  20119. this.postProcesses[0].dispose();
  20120. }
  20121. // Release layers
  20122. while (this.layers.length) {
  20123. this.layers[0].dispose();
  20124. }
  20125. while (this.highlightLayers.length) {
  20126. this.highlightLayers[0].dispose();
  20127. }
  20128. // Release textures
  20129. while (this.textures.length) {
  20130. this.textures[0].dispose();
  20131. }
  20132. // Release UBO
  20133. this._sceneUbo.dispose();
  20134. if (this._alternateSceneUbo) {
  20135. this._alternateSceneUbo.dispose();
  20136. }
  20137. // Post-processes
  20138. this.postProcessManager.dispose();
  20139. if (this._postProcessRenderPipelineManager) {
  20140. this._postProcessRenderPipelineManager.dispose();
  20141. }
  20142. // Physics
  20143. if (this._physicsEngine) {
  20144. this.disablePhysicsEngine();
  20145. }
  20146. // Remove from engine
  20147. index = this._engine.scenes.indexOf(this);
  20148. if (index > -1) {
  20149. this._engine.scenes.splice(index, 1);
  20150. }
  20151. this._engine.wipeCaches();
  20152. this._isDisposed = true;
  20153. };
  20154. Object.defineProperty(Scene.prototype, "isDisposed", {
  20155. get: function () {
  20156. return this._isDisposed;
  20157. },
  20158. enumerable: true,
  20159. configurable: true
  20160. });
  20161. // Release sounds & sounds tracks
  20162. Scene.prototype.disposeSounds = function () {
  20163. if (!this._mainSoundTrack) {
  20164. return;
  20165. }
  20166. this.mainSoundTrack.dispose();
  20167. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20168. this.soundTracks[scIndex].dispose();
  20169. }
  20170. };
  20171. // Octrees
  20172. Scene.prototype.getWorldExtends = function () {
  20173. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20174. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20175. for (var index = 0; index < this.meshes.length; index++) {
  20176. var mesh = this.meshes[index];
  20177. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20178. continue;
  20179. }
  20180. mesh.computeWorldMatrix(true);
  20181. var boundingInfo = mesh.getBoundingInfo();
  20182. if (boundingInfo) {
  20183. var minBox = boundingInfo.boundingBox.minimumWorld;
  20184. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20185. BABYLON.Tools.CheckExtends(minBox, min, max);
  20186. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20187. }
  20188. }
  20189. return {
  20190. min: min,
  20191. max: max
  20192. };
  20193. };
  20194. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20195. if (maxCapacity === void 0) { maxCapacity = 64; }
  20196. if (maxDepth === void 0) { maxDepth = 2; }
  20197. if (!this._selectionOctree) {
  20198. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20199. }
  20200. var worldExtends = this.getWorldExtends();
  20201. // Update octree
  20202. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20203. return this._selectionOctree;
  20204. };
  20205. // Picking
  20206. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20207. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20208. var engine = this._engine;
  20209. if (!camera) {
  20210. if (!this.activeCamera)
  20211. throw new Error("Active camera not set");
  20212. camera = this.activeCamera;
  20213. }
  20214. var cameraViewport = camera.viewport;
  20215. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20216. // Moving coordinates to local viewport world
  20217. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20218. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20219. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20220. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20221. };
  20222. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20223. if (!BABYLON.PickingInfo) {
  20224. return null;
  20225. }
  20226. var engine = this._engine;
  20227. if (!camera) {
  20228. if (!this.activeCamera)
  20229. throw new Error("Active camera not set");
  20230. camera = this.activeCamera;
  20231. }
  20232. var cameraViewport = camera.viewport;
  20233. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20234. var identity = BABYLON.Matrix.Identity();
  20235. // Moving coordinates to local viewport world
  20236. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20237. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20238. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20239. };
  20240. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20241. if (!BABYLON.PickingInfo) {
  20242. return null;
  20243. }
  20244. var pickingInfo = null;
  20245. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20246. var mesh = this.meshes[meshIndex];
  20247. if (predicate) {
  20248. if (!predicate(mesh)) {
  20249. continue;
  20250. }
  20251. }
  20252. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20253. continue;
  20254. }
  20255. var world = mesh.getWorldMatrix();
  20256. var ray = rayFunction(world);
  20257. var result = mesh.intersects(ray, fastCheck);
  20258. if (!result || !result.hit)
  20259. continue;
  20260. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20261. continue;
  20262. pickingInfo = result;
  20263. if (fastCheck) {
  20264. break;
  20265. }
  20266. }
  20267. return pickingInfo || new BABYLON.PickingInfo();
  20268. };
  20269. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20270. if (!BABYLON.PickingInfo) {
  20271. return null;
  20272. }
  20273. var pickingInfos = new Array();
  20274. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20275. var mesh = this.meshes[meshIndex];
  20276. if (predicate) {
  20277. if (!predicate(mesh)) {
  20278. continue;
  20279. }
  20280. }
  20281. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20282. continue;
  20283. }
  20284. var world = mesh.getWorldMatrix();
  20285. var ray = rayFunction(world);
  20286. var result = mesh.intersects(ray, false);
  20287. if (!result || !result.hit)
  20288. continue;
  20289. pickingInfos.push(result);
  20290. }
  20291. return pickingInfos;
  20292. };
  20293. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20294. if (!BABYLON.PickingInfo) {
  20295. return null;
  20296. }
  20297. var pickingInfo = null;
  20298. if (!camera) {
  20299. if (!this.activeCamera) {
  20300. return null;
  20301. }
  20302. camera = this.activeCamera;
  20303. }
  20304. if (this.spriteManagers.length > 0) {
  20305. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20306. var spriteManager = this.spriteManagers[spriteIndex];
  20307. if (!spriteManager.isPickable) {
  20308. continue;
  20309. }
  20310. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20311. if (!result || !result.hit)
  20312. continue;
  20313. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20314. continue;
  20315. pickingInfo = result;
  20316. if (fastCheck) {
  20317. break;
  20318. }
  20319. }
  20320. }
  20321. return pickingInfo || new BABYLON.PickingInfo();
  20322. };
  20323. /** Launch a ray to try to pick a mesh in the scene
  20324. * @param x position on screen
  20325. * @param y position on screen
  20326. * @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
  20327. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20328. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20329. */
  20330. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20331. var _this = this;
  20332. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20333. };
  20334. /** Launch a ray to try to pick a sprite in the scene
  20335. * @param x position on screen
  20336. * @param y position on screen
  20337. * @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
  20338. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20339. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20340. */
  20341. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20342. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20343. if (!ray) {
  20344. return null;
  20345. }
  20346. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20347. };
  20348. /** Use the given ray to pick a mesh in the scene
  20349. * @param ray The ray to use to pick meshes
  20350. * @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
  20351. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20352. */
  20353. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20354. var _this = this;
  20355. return this._internalPick(function (world) {
  20356. if (!_this._pickWithRayInverseMatrix) {
  20357. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20358. }
  20359. world.invertToRef(_this._pickWithRayInverseMatrix);
  20360. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20361. }, predicate, fastCheck);
  20362. };
  20363. /**
  20364. * Launch a ray to try to pick a mesh in the scene
  20365. * @param x X position on screen
  20366. * @param y Y position on screen
  20367. * @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
  20368. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20369. */
  20370. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20371. var _this = this;
  20372. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20373. };
  20374. /**
  20375. * Launch a ray to try to pick a mesh in the scene
  20376. * @param ray Ray to use
  20377. * @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
  20378. */
  20379. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20380. var _this = this;
  20381. return this._internalMultiPick(function (world) {
  20382. if (!_this._pickWithRayInverseMatrix) {
  20383. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20384. }
  20385. world.invertToRef(_this._pickWithRayInverseMatrix);
  20386. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20387. }, predicate);
  20388. };
  20389. Scene.prototype.setPointerOverMesh = function (mesh) {
  20390. if (this._pointerOverMesh === mesh) {
  20391. return;
  20392. }
  20393. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20394. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20395. }
  20396. this._pointerOverMesh = mesh;
  20397. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20398. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20399. }
  20400. };
  20401. Scene.prototype.getPointerOverMesh = function () {
  20402. return this._pointerOverMesh;
  20403. };
  20404. Scene.prototype.setPointerOverSprite = function (sprite) {
  20405. if (this._pointerOverSprite === sprite) {
  20406. return;
  20407. }
  20408. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20409. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20410. }
  20411. this._pointerOverSprite = sprite;
  20412. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20413. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20414. }
  20415. };
  20416. Scene.prototype.getPointerOverSprite = function () {
  20417. return this._pointerOverSprite;
  20418. };
  20419. // Physics
  20420. Scene.prototype.getPhysicsEngine = function () {
  20421. return this._physicsEngine;
  20422. };
  20423. /**
  20424. * Enables physics to the current scene
  20425. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20426. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20427. * @return {boolean} was the physics engine initialized
  20428. */
  20429. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20430. if (gravity === void 0) { gravity = null; }
  20431. if (this._physicsEngine) {
  20432. return true;
  20433. }
  20434. try {
  20435. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20436. return true;
  20437. }
  20438. catch (e) {
  20439. BABYLON.Tools.Error(e.message);
  20440. return false;
  20441. }
  20442. };
  20443. Scene.prototype.disablePhysicsEngine = function () {
  20444. if (!this._physicsEngine) {
  20445. return;
  20446. }
  20447. this._physicsEngine.dispose();
  20448. this._physicsEngine = null;
  20449. };
  20450. Scene.prototype.isPhysicsEnabled = function () {
  20451. return this._physicsEngine !== undefined;
  20452. };
  20453. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20454. var mesh = compound.parts[0].mesh;
  20455. if (mesh.physicsImpostor) {
  20456. mesh.physicsImpostor.dispose();
  20457. mesh.physicsImpostor = null;
  20458. }
  20459. };
  20460. // Misc.
  20461. Scene.prototype._rebuildGeometries = function () {
  20462. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20463. var geometry = _a[_i];
  20464. geometry._rebuild();
  20465. }
  20466. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20467. var mesh = _c[_b];
  20468. mesh._rebuild();
  20469. }
  20470. if (this.postProcessManager) {
  20471. this.postProcessManager._rebuild();
  20472. }
  20473. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20474. var layer = _e[_d];
  20475. layer._rebuild();
  20476. }
  20477. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20478. var highlightLayer = _g[_f];
  20479. highlightLayer._rebuild();
  20480. }
  20481. if (this._boundingBoxRenderer) {
  20482. this._boundingBoxRenderer._rebuild();
  20483. }
  20484. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20485. var system = _j[_h];
  20486. system.rebuild();
  20487. }
  20488. if (this._postProcessRenderPipelineManager) {
  20489. this._postProcessRenderPipelineManager._rebuild();
  20490. }
  20491. };
  20492. Scene.prototype._rebuildTextures = function () {
  20493. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20494. var texture = _a[_i];
  20495. texture._rebuild();
  20496. }
  20497. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20498. };
  20499. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20500. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20501. if (replace === void 0) { replace = false; }
  20502. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20503. // Dispose existing camera or light in replace mode.
  20504. if (replace) {
  20505. if (this.activeCamera) {
  20506. this.activeCamera.dispose();
  20507. this.activeCamera = null;
  20508. }
  20509. if (this.lights) {
  20510. for (var i = 0; i < this.lights.length; i++) {
  20511. this.lights[i].dispose();
  20512. }
  20513. }
  20514. }
  20515. // Light
  20516. if (this.lights.length === 0) {
  20517. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20518. }
  20519. // Camera
  20520. if (!this.activeCamera) {
  20521. var worldExtends = this.getWorldExtends();
  20522. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20523. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20524. var camera;
  20525. var radius = worldSize.length() * 1.5;
  20526. if (createArcRotateCamera) {
  20527. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20528. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20529. arcRotateCamera.wheelPrecision = 100 / radius;
  20530. camera = arcRotateCamera;
  20531. }
  20532. else {
  20533. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20534. freeCamera.setTarget(worldCenter);
  20535. camera = freeCamera;
  20536. }
  20537. camera.minZ = radius * 0.01;
  20538. camera.maxZ = radius * 100;
  20539. camera.speed = radius * 0.2;
  20540. this.activeCamera = camera;
  20541. var canvas = this.getEngine().getRenderingCanvas();
  20542. if (attachCameraControls && canvas) {
  20543. camera.attachControl(canvas);
  20544. }
  20545. }
  20546. };
  20547. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20548. if (pbr === void 0) { pbr = false; }
  20549. if (scale === void 0) { scale = 1000; }
  20550. if (blur === void 0) { blur = 0; }
  20551. if (environmentTexture) {
  20552. this.environmentTexture = environmentTexture;
  20553. }
  20554. if (!this.environmentTexture) {
  20555. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20556. return null;
  20557. }
  20558. // Skybox
  20559. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20560. if (pbr) {
  20561. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20562. hdrSkyboxMaterial.backFaceCulling = false;
  20563. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20564. if (hdrSkyboxMaterial.reflectionTexture) {
  20565. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20566. }
  20567. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20568. hdrSkyboxMaterial.disableLighting = true;
  20569. hdrSkyboxMaterial.twoSidedLighting = true;
  20570. hdrSkybox.infiniteDistance = true;
  20571. hdrSkybox.material = hdrSkyboxMaterial;
  20572. }
  20573. else {
  20574. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20575. skyboxMaterial.backFaceCulling = false;
  20576. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20577. if (skyboxMaterial.reflectionTexture) {
  20578. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20579. }
  20580. skyboxMaterial.disableLighting = true;
  20581. hdrSkybox.infiniteDistance = true;
  20582. hdrSkybox.material = skyboxMaterial;
  20583. }
  20584. return hdrSkybox;
  20585. };
  20586. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20587. if (webVROptions === void 0) { webVROptions = {}; }
  20588. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20589. };
  20590. // Tags
  20591. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20592. if (tagsQuery === undefined) {
  20593. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20594. return list;
  20595. }
  20596. var listByTags = [];
  20597. forEach = forEach || (function (item) { return; });
  20598. for (var i in list) {
  20599. var item = list[i];
  20600. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20601. listByTags.push(item);
  20602. forEach(item);
  20603. }
  20604. }
  20605. return listByTags;
  20606. };
  20607. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20608. return this._getByTags(this.meshes, tagsQuery, forEach);
  20609. };
  20610. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20611. return this._getByTags(this.cameras, tagsQuery, forEach);
  20612. };
  20613. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20614. return this._getByTags(this.lights, tagsQuery, forEach);
  20615. };
  20616. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20617. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20618. };
  20619. /**
  20620. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20621. * This allowed control for front to back rendering or reversly depending of the special needs.
  20622. *
  20623. * @param renderingGroupId The rendering group id corresponding to its index
  20624. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20625. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20626. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20627. */
  20628. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20629. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20630. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20631. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20632. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20633. };
  20634. /**
  20635. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20636. *
  20637. * @param renderingGroupId The rendering group id corresponding to its index
  20638. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20639. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20640. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20641. */
  20642. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20643. if (depth === void 0) { depth = true; }
  20644. if (stencil === void 0) { stencil = true; }
  20645. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20646. };
  20647. /**
  20648. * Will flag all materials as dirty to trigger new shader compilation
  20649. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20650. */
  20651. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20652. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20653. var material = _a[_i];
  20654. if (predicate && !predicate(material)) {
  20655. continue;
  20656. }
  20657. material.markAsDirty(flag);
  20658. }
  20659. };
  20660. // Statics
  20661. Scene._FOGMODE_NONE = 0;
  20662. Scene._FOGMODE_EXP = 1;
  20663. Scene._FOGMODE_EXP2 = 2;
  20664. Scene._FOGMODE_LINEAR = 3;
  20665. Scene._uniqueIdCounter = 0;
  20666. Scene.MinDeltaTime = 1.0;
  20667. Scene.MaxDeltaTime = 1000.0;
  20668. /** The distance in pixel that you have to move to prevent some events */
  20669. Scene.DragMovementThreshold = 10; // in pixels
  20670. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20671. Scene.LongPressDelay = 500; // in milliseconds
  20672. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20673. Scene.DoubleClickDelay = 300; // in milliseconds
  20674. /** If you need to check double click without raising a single click at first click, enable this flag */
  20675. Scene.ExclusiveDoubleClickMode = false;
  20676. return Scene;
  20677. }());
  20678. BABYLON.Scene = Scene;
  20679. })(BABYLON || (BABYLON = {}));
  20680. //# sourceMappingURL=babylon.scene.js.map
  20681. var BABYLON;
  20682. (function (BABYLON) {
  20683. var Buffer = /** @class */ (function () {
  20684. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20685. if (instanced === void 0) { instanced = false; }
  20686. if (engine instanceof BABYLON.Mesh) {
  20687. this._engine = engine.getScene().getEngine();
  20688. }
  20689. else {
  20690. this._engine = engine;
  20691. }
  20692. this._updatable = updatable;
  20693. this._data = data;
  20694. this._strideSize = stride;
  20695. if (!postponeInternalCreation) {
  20696. this.create();
  20697. }
  20698. this._instanced = instanced;
  20699. this._instanceDivisor = instanced ? 1 : 0;
  20700. }
  20701. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20702. // a lot of these parameters are ignored as they are overriden by the buffer
  20703. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20704. };
  20705. // Properties
  20706. Buffer.prototype.isUpdatable = function () {
  20707. return this._updatable;
  20708. };
  20709. Buffer.prototype.getData = function () {
  20710. return this._data;
  20711. };
  20712. Buffer.prototype.getBuffer = function () {
  20713. return this._buffer;
  20714. };
  20715. Buffer.prototype.getStrideSize = function () {
  20716. return this._strideSize;
  20717. };
  20718. Buffer.prototype.getIsInstanced = function () {
  20719. return this._instanced;
  20720. };
  20721. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20722. get: function () {
  20723. return this._instanceDivisor;
  20724. },
  20725. set: function (value) {
  20726. this._instanceDivisor = value;
  20727. if (value == 0) {
  20728. this._instanced = false;
  20729. }
  20730. else {
  20731. this._instanced = true;
  20732. }
  20733. },
  20734. enumerable: true,
  20735. configurable: true
  20736. });
  20737. // Methods
  20738. Buffer.prototype.create = function (data) {
  20739. if (data === void 0) { data = null; }
  20740. if (!data && this._buffer) {
  20741. return; // nothing to do
  20742. }
  20743. data = data || this._data;
  20744. if (!data) {
  20745. return;
  20746. }
  20747. if (!this._buffer) {
  20748. if (this._updatable) {
  20749. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20750. this._data = data;
  20751. }
  20752. else {
  20753. this._buffer = this._engine.createVertexBuffer(data);
  20754. }
  20755. }
  20756. else if (this._updatable) {
  20757. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20758. this._data = data;
  20759. }
  20760. };
  20761. Buffer.prototype._rebuild = function () {
  20762. this._buffer = null;
  20763. this.create(this._data);
  20764. };
  20765. Buffer.prototype.update = function (data) {
  20766. this.create(data);
  20767. };
  20768. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20769. if (!this._buffer) {
  20770. return;
  20771. }
  20772. if (this._updatable) {
  20773. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20774. this._data = null;
  20775. }
  20776. };
  20777. Buffer.prototype.dispose = function () {
  20778. if (!this._buffer) {
  20779. return;
  20780. }
  20781. if (this._engine._releaseBuffer(this._buffer)) {
  20782. this._buffer = null;
  20783. }
  20784. };
  20785. return Buffer;
  20786. }());
  20787. BABYLON.Buffer = Buffer;
  20788. })(BABYLON || (BABYLON = {}));
  20789. //# sourceMappingURL=babylon.buffer.js.map
  20790. var BABYLON;
  20791. (function (BABYLON) {
  20792. var VertexBuffer = /** @class */ (function () {
  20793. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20794. if (!stride) {
  20795. // Deduce stride from kind
  20796. switch (kind) {
  20797. case VertexBuffer.PositionKind:
  20798. stride = 3;
  20799. break;
  20800. case VertexBuffer.NormalKind:
  20801. stride = 3;
  20802. break;
  20803. case VertexBuffer.UVKind:
  20804. case VertexBuffer.UV2Kind:
  20805. case VertexBuffer.UV3Kind:
  20806. case VertexBuffer.UV4Kind:
  20807. case VertexBuffer.UV5Kind:
  20808. case VertexBuffer.UV6Kind:
  20809. stride = 2;
  20810. break;
  20811. case VertexBuffer.TangentKind:
  20812. case VertexBuffer.ColorKind:
  20813. stride = 4;
  20814. break;
  20815. case VertexBuffer.MatricesIndicesKind:
  20816. case VertexBuffer.MatricesIndicesExtraKind:
  20817. stride = 4;
  20818. break;
  20819. case VertexBuffer.MatricesWeightsKind:
  20820. case VertexBuffer.MatricesWeightsExtraKind:
  20821. default:
  20822. stride = 4;
  20823. break;
  20824. }
  20825. }
  20826. if (data instanceof BABYLON.Buffer) {
  20827. if (!stride) {
  20828. stride = data.getStrideSize();
  20829. }
  20830. this._buffer = data;
  20831. this._ownsBuffer = false;
  20832. }
  20833. else {
  20834. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20835. this._ownsBuffer = true;
  20836. }
  20837. this._stride = stride;
  20838. this._offset = offset ? offset : 0;
  20839. this._size = size ? size : stride;
  20840. this._kind = kind;
  20841. }
  20842. VertexBuffer.prototype._rebuild = function () {
  20843. if (!this._buffer) {
  20844. return;
  20845. }
  20846. this._buffer._rebuild();
  20847. };
  20848. /**
  20849. * Returns the kind of the VertexBuffer (string).
  20850. */
  20851. VertexBuffer.prototype.getKind = function () {
  20852. return this._kind;
  20853. };
  20854. // Properties
  20855. /**
  20856. * Boolean : is the VertexBuffer updatable ?
  20857. */
  20858. VertexBuffer.prototype.isUpdatable = function () {
  20859. return this._buffer.isUpdatable();
  20860. };
  20861. /**
  20862. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20863. */
  20864. VertexBuffer.prototype.getData = function () {
  20865. return this._buffer.getData();
  20866. };
  20867. /**
  20868. * Returns the WebGLBuffer associated to the VertexBuffer.
  20869. */
  20870. VertexBuffer.prototype.getBuffer = function () {
  20871. return this._buffer.getBuffer();
  20872. };
  20873. /**
  20874. * Returns the stride of the VertexBuffer (integer).
  20875. */
  20876. VertexBuffer.prototype.getStrideSize = function () {
  20877. return this._stride;
  20878. };
  20879. /**
  20880. * Returns the offset (integer).
  20881. */
  20882. VertexBuffer.prototype.getOffset = function () {
  20883. return this._offset;
  20884. };
  20885. /**
  20886. * Returns the VertexBuffer total size (integer).
  20887. */
  20888. VertexBuffer.prototype.getSize = function () {
  20889. return this._size;
  20890. };
  20891. /**
  20892. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20893. */
  20894. VertexBuffer.prototype.getIsInstanced = function () {
  20895. return this._buffer.getIsInstanced();
  20896. };
  20897. /**
  20898. * Returns the instancing divisor, zero for non-instanced (integer).
  20899. */
  20900. VertexBuffer.prototype.getInstanceDivisor = function () {
  20901. return this._buffer.instanceDivisor;
  20902. };
  20903. // Methods
  20904. /**
  20905. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20906. * Returns the created WebGLBuffer.
  20907. */
  20908. VertexBuffer.prototype.create = function (data) {
  20909. return this._buffer.create(data);
  20910. };
  20911. /**
  20912. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20913. * Returns the updated WebGLBuffer.
  20914. */
  20915. VertexBuffer.prototype.update = function (data) {
  20916. return this._buffer.update(data);
  20917. };
  20918. /**
  20919. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20920. * Returns the directly updated WebGLBuffer.
  20921. */
  20922. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20923. return this._buffer.updateDirectly(data, offset);
  20924. };
  20925. /**
  20926. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20927. */
  20928. VertexBuffer.prototype.dispose = function () {
  20929. if (this._ownsBuffer) {
  20930. this._buffer.dispose();
  20931. }
  20932. };
  20933. Object.defineProperty(VertexBuffer, "PositionKind", {
  20934. get: function () {
  20935. return VertexBuffer._PositionKind;
  20936. },
  20937. enumerable: true,
  20938. configurable: true
  20939. });
  20940. Object.defineProperty(VertexBuffer, "NormalKind", {
  20941. get: function () {
  20942. return VertexBuffer._NormalKind;
  20943. },
  20944. enumerable: true,
  20945. configurable: true
  20946. });
  20947. Object.defineProperty(VertexBuffer, "TangentKind", {
  20948. get: function () {
  20949. return VertexBuffer._TangentKind;
  20950. },
  20951. enumerable: true,
  20952. configurable: true
  20953. });
  20954. Object.defineProperty(VertexBuffer, "UVKind", {
  20955. get: function () {
  20956. return VertexBuffer._UVKind;
  20957. },
  20958. enumerable: true,
  20959. configurable: true
  20960. });
  20961. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20962. get: function () {
  20963. return VertexBuffer._UV2Kind;
  20964. },
  20965. enumerable: true,
  20966. configurable: true
  20967. });
  20968. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20969. get: function () {
  20970. return VertexBuffer._UV3Kind;
  20971. },
  20972. enumerable: true,
  20973. configurable: true
  20974. });
  20975. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20976. get: function () {
  20977. return VertexBuffer._UV4Kind;
  20978. },
  20979. enumerable: true,
  20980. configurable: true
  20981. });
  20982. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20983. get: function () {
  20984. return VertexBuffer._UV5Kind;
  20985. },
  20986. enumerable: true,
  20987. configurable: true
  20988. });
  20989. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20990. get: function () {
  20991. return VertexBuffer._UV6Kind;
  20992. },
  20993. enumerable: true,
  20994. configurable: true
  20995. });
  20996. Object.defineProperty(VertexBuffer, "ColorKind", {
  20997. get: function () {
  20998. return VertexBuffer._ColorKind;
  20999. },
  21000. enumerable: true,
  21001. configurable: true
  21002. });
  21003. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21004. get: function () {
  21005. return VertexBuffer._MatricesIndicesKind;
  21006. },
  21007. enumerable: true,
  21008. configurable: true
  21009. });
  21010. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21011. get: function () {
  21012. return VertexBuffer._MatricesWeightsKind;
  21013. },
  21014. enumerable: true,
  21015. configurable: true
  21016. });
  21017. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21018. get: function () {
  21019. return VertexBuffer._MatricesIndicesExtraKind;
  21020. },
  21021. enumerable: true,
  21022. configurable: true
  21023. });
  21024. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21025. get: function () {
  21026. return VertexBuffer._MatricesWeightsExtraKind;
  21027. },
  21028. enumerable: true,
  21029. configurable: true
  21030. });
  21031. // Enums
  21032. VertexBuffer._PositionKind = "position";
  21033. VertexBuffer._NormalKind = "normal";
  21034. VertexBuffer._TangentKind = "tangent";
  21035. VertexBuffer._UVKind = "uv";
  21036. VertexBuffer._UV2Kind = "uv2";
  21037. VertexBuffer._UV3Kind = "uv3";
  21038. VertexBuffer._UV4Kind = "uv4";
  21039. VertexBuffer._UV5Kind = "uv5";
  21040. VertexBuffer._UV6Kind = "uv6";
  21041. VertexBuffer._ColorKind = "color";
  21042. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21043. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21044. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21045. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21046. return VertexBuffer;
  21047. }());
  21048. BABYLON.VertexBuffer = VertexBuffer;
  21049. })(BABYLON || (BABYLON = {}));
  21050. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21051. var BABYLON;
  21052. (function (BABYLON) {
  21053. var InternalTexture = /** @class */ (function () {
  21054. function InternalTexture(engine, dataSource) {
  21055. this.onLoadedObservable = new BABYLON.Observable();
  21056. // Private
  21057. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21058. this._references = 1;
  21059. this._engine = engine;
  21060. this._dataSource = dataSource;
  21061. this._webGLTexture = engine._createTexture();
  21062. }
  21063. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21064. get: function () {
  21065. return this._dataSource;
  21066. },
  21067. enumerable: true,
  21068. configurable: true
  21069. });
  21070. InternalTexture.prototype.incrementReferences = function () {
  21071. this._references++;
  21072. };
  21073. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21074. if (depth === void 0) { depth = 1; }
  21075. this.width = width;
  21076. this.height = height;
  21077. this.depth = depth;
  21078. this.baseWidth = width;
  21079. this.baseHeight = height;
  21080. this.baseDepth = depth;
  21081. this._size = width * height * depth;
  21082. };
  21083. InternalTexture.prototype._rebuild = function () {
  21084. var _this = this;
  21085. var proxy;
  21086. this.isReady = false;
  21087. this._cachedCoordinatesMode = null;
  21088. this._cachedWrapU = null;
  21089. this._cachedWrapV = null;
  21090. this._cachedAnisotropicFilteringLevel = null;
  21091. switch (this._dataSource) {
  21092. case InternalTexture.DATASOURCE_TEMP:
  21093. return;
  21094. case InternalTexture.DATASOURCE_URL:
  21095. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21096. _this.isReady = true;
  21097. }, null, this._buffer, undefined, this.format);
  21098. proxy._swapAndDie(this);
  21099. return;
  21100. case InternalTexture.DATASOURCE_RAW:
  21101. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21102. proxy._swapAndDie(this);
  21103. this.isReady = true;
  21104. return;
  21105. case InternalTexture.DATASOURCE_RAW3D:
  21106. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21107. proxy._swapAndDie(this);
  21108. this.isReady = true;
  21109. return;
  21110. case InternalTexture.DATASOURCE_DYNAMIC:
  21111. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21112. proxy._swapAndDie(this);
  21113. // The engine will make sure to update content so no need to flag it as isReady = true
  21114. return;
  21115. case InternalTexture.DATASOURCE_RENDERTARGET:
  21116. var options = new BABYLON.RenderTargetCreationOptions();
  21117. options.generateDepthBuffer = this._generateDepthBuffer;
  21118. options.generateMipMaps = this.generateMipMaps;
  21119. options.generateStencilBuffer = this._generateStencilBuffer;
  21120. options.samplingMode = this.samplingMode;
  21121. options.type = this.type;
  21122. if (this.isCube) {
  21123. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21124. }
  21125. else {
  21126. var size = {
  21127. width: this.width,
  21128. height: this.height
  21129. };
  21130. proxy = this._engine.createRenderTargetTexture(size, options);
  21131. }
  21132. proxy._swapAndDie(this);
  21133. this.isReady = true;
  21134. return;
  21135. case InternalTexture.DATASOURCE_CUBE:
  21136. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21137. _this.isReady = true;
  21138. }, null, this.format, this._extension);
  21139. proxy._swapAndDie(this);
  21140. return;
  21141. case InternalTexture.DATASOURCE_CUBERAW:
  21142. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21143. proxy._swapAndDie(this);
  21144. this.isReady = true;
  21145. return;
  21146. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21147. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21148. if (proxy) {
  21149. proxy._swapAndDie(_this);
  21150. }
  21151. _this.isReady = true;
  21152. }, null, this.format, this._extension);
  21153. return;
  21154. }
  21155. };
  21156. InternalTexture.prototype._swapAndDie = function (target) {
  21157. target._webGLTexture = this._webGLTexture;
  21158. if (this._framebuffer) {
  21159. target._framebuffer = this._framebuffer;
  21160. }
  21161. if (this._depthStencilBuffer) {
  21162. target._depthStencilBuffer = this._depthStencilBuffer;
  21163. }
  21164. if (this._lodTextureHigh) {
  21165. if (target._lodTextureHigh) {
  21166. target._lodTextureHigh.dispose();
  21167. }
  21168. target._lodTextureHigh = this._lodTextureHigh;
  21169. }
  21170. if (this._lodTextureMid) {
  21171. if (target._lodTextureMid) {
  21172. target._lodTextureMid.dispose();
  21173. }
  21174. target._lodTextureMid = this._lodTextureMid;
  21175. }
  21176. if (this._lodTextureLow) {
  21177. if (target._lodTextureLow) {
  21178. target._lodTextureLow.dispose();
  21179. }
  21180. target._lodTextureLow = this._lodTextureLow;
  21181. }
  21182. var cache = this._engine.getLoadedTexturesCache();
  21183. var index = cache.indexOf(this);
  21184. if (index !== -1) {
  21185. cache.splice(index, 1);
  21186. }
  21187. };
  21188. InternalTexture.prototype.dispose = function () {
  21189. if (!this._webGLTexture) {
  21190. return;
  21191. }
  21192. this._references--;
  21193. if (this._references === 0) {
  21194. this._engine._releaseTexture(this);
  21195. this._webGLTexture = null;
  21196. }
  21197. };
  21198. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21199. InternalTexture.DATASOURCE_URL = 1;
  21200. InternalTexture.DATASOURCE_TEMP = 2;
  21201. InternalTexture.DATASOURCE_RAW = 3;
  21202. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21203. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21204. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21205. InternalTexture.DATASOURCE_CUBE = 7;
  21206. InternalTexture.DATASOURCE_CUBERAW = 8;
  21207. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21208. InternalTexture.DATASOURCE_RAW3D = 10;
  21209. return InternalTexture;
  21210. }());
  21211. BABYLON.InternalTexture = InternalTexture;
  21212. })(BABYLON || (BABYLON = {}));
  21213. //# sourceMappingURL=babylon.internalTexture.js.map
  21214. var BABYLON;
  21215. (function (BABYLON) {
  21216. var BaseTexture = /** @class */ (function () {
  21217. function BaseTexture(scene) {
  21218. this._hasAlpha = false;
  21219. this.getAlphaFromRGB = false;
  21220. this.level = 1;
  21221. this.coordinatesIndex = 0;
  21222. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21223. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21224. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21225. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21226. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21227. this.isCube = false;
  21228. this.is3D = false;
  21229. this.gammaSpace = true;
  21230. this.invertZ = false;
  21231. this.lodLevelInAlpha = false;
  21232. this.lodGenerationOffset = 0.0;
  21233. this.lodGenerationScale = 0.8;
  21234. this.isRenderTarget = false;
  21235. this.animations = new Array();
  21236. /**
  21237. * An event triggered when the texture is disposed.
  21238. * @type {BABYLON.Observable}
  21239. */
  21240. this.onDisposeObservable = new BABYLON.Observable();
  21241. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21242. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21243. if (this._scene) {
  21244. this._scene.textures.push(this);
  21245. }
  21246. this._uid = null;
  21247. }
  21248. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21249. get: function () {
  21250. return this._hasAlpha;
  21251. },
  21252. set: function (value) {
  21253. if (this._hasAlpha === value) {
  21254. return;
  21255. }
  21256. this._hasAlpha = value;
  21257. if (this._scene) {
  21258. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21259. }
  21260. },
  21261. enumerable: true,
  21262. configurable: true
  21263. });
  21264. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21265. get: function () {
  21266. return this._coordinatesMode;
  21267. },
  21268. set: function (value) {
  21269. if (this._coordinatesMode === value) {
  21270. return;
  21271. }
  21272. this._coordinatesMode = value;
  21273. if (this._scene) {
  21274. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21275. }
  21276. },
  21277. enumerable: true,
  21278. configurable: true
  21279. });
  21280. Object.defineProperty(BaseTexture.prototype, "uid", {
  21281. get: function () {
  21282. if (!this._uid) {
  21283. this._uid = BABYLON.Tools.RandomId();
  21284. }
  21285. return this._uid;
  21286. },
  21287. enumerable: true,
  21288. configurable: true
  21289. });
  21290. BaseTexture.prototype.toString = function () {
  21291. return this.name;
  21292. };
  21293. BaseTexture.prototype.getClassName = function () {
  21294. return "BaseTexture";
  21295. };
  21296. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21297. set: function (callback) {
  21298. if (this._onDisposeObserver) {
  21299. this.onDisposeObservable.remove(this._onDisposeObserver);
  21300. }
  21301. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21307. get: function () {
  21308. return true;
  21309. },
  21310. enumerable: true,
  21311. configurable: true
  21312. });
  21313. BaseTexture.prototype.getScene = function () {
  21314. return this._scene;
  21315. };
  21316. BaseTexture.prototype.getTextureMatrix = function () {
  21317. return BABYLON.Matrix.IdentityReadOnly;
  21318. };
  21319. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21320. return BABYLON.Matrix.IdentityReadOnly;
  21321. };
  21322. BaseTexture.prototype.getInternalTexture = function () {
  21323. return this._texture;
  21324. };
  21325. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21326. return !this.isBlocking || this.isReady();
  21327. };
  21328. BaseTexture.prototype.isReady = function () {
  21329. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21330. this.delayLoad();
  21331. return false;
  21332. }
  21333. if (this._texture) {
  21334. return this._texture.isReady;
  21335. }
  21336. return false;
  21337. };
  21338. BaseTexture.prototype.getSize = function () {
  21339. if (this._texture && this._texture.width) {
  21340. return new BABYLON.Size(this._texture.width, this._texture.height);
  21341. }
  21342. if (this._texture && this._texture._size) {
  21343. return new BABYLON.Size(this._texture._size, this._texture._size);
  21344. }
  21345. return BABYLON.Size.Zero();
  21346. };
  21347. BaseTexture.prototype.getBaseSize = function () {
  21348. if (!this.isReady() || !this._texture)
  21349. return BABYLON.Size.Zero();
  21350. if (this._texture._size) {
  21351. return new BABYLON.Size(this._texture._size, this._texture._size);
  21352. }
  21353. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21354. };
  21355. BaseTexture.prototype.scale = function (ratio) {
  21356. };
  21357. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21358. get: function () {
  21359. return false;
  21360. },
  21361. enumerable: true,
  21362. configurable: true
  21363. });
  21364. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21365. if (!this._scene) {
  21366. return null;
  21367. }
  21368. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21369. for (var index = 0; index < texturesCache.length; index++) {
  21370. var texturesCacheEntry = texturesCache[index];
  21371. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21372. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21373. texturesCacheEntry.incrementReferences();
  21374. return texturesCacheEntry;
  21375. }
  21376. }
  21377. }
  21378. return null;
  21379. };
  21380. BaseTexture.prototype._rebuild = function () {
  21381. };
  21382. BaseTexture.prototype.delayLoad = function () {
  21383. };
  21384. BaseTexture.prototype.clone = function () {
  21385. return null;
  21386. };
  21387. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21388. get: function () {
  21389. if (!this._texture) {
  21390. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21391. }
  21392. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21393. },
  21394. enumerable: true,
  21395. configurable: true
  21396. });
  21397. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21398. get: function () {
  21399. if (!this._texture) {
  21400. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21401. }
  21402. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21403. },
  21404. enumerable: true,
  21405. configurable: true
  21406. });
  21407. BaseTexture.prototype.readPixels = function (faceIndex) {
  21408. if (faceIndex === void 0) { faceIndex = 0; }
  21409. if (!this._texture) {
  21410. return null;
  21411. }
  21412. var size = this.getSize();
  21413. var scene = this.getScene();
  21414. if (!scene) {
  21415. return null;
  21416. }
  21417. var engine = scene.getEngine();
  21418. if (this._texture.isCube) {
  21419. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21420. }
  21421. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21422. };
  21423. BaseTexture.prototype.releaseInternalTexture = function () {
  21424. if (this._texture) {
  21425. this._texture.dispose();
  21426. this._texture = null;
  21427. }
  21428. };
  21429. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21430. get: function () {
  21431. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21432. return null;
  21433. }
  21434. if (!this._texture._sphericalPolynomial) {
  21435. this._texture._sphericalPolynomial =
  21436. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21437. }
  21438. return this._texture._sphericalPolynomial;
  21439. },
  21440. set: function (value) {
  21441. if (this._texture) {
  21442. this._texture._sphericalPolynomial = value;
  21443. }
  21444. },
  21445. enumerable: true,
  21446. configurable: true
  21447. });
  21448. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21449. get: function () {
  21450. if (this._texture) {
  21451. return this._texture._lodTextureHigh;
  21452. }
  21453. return null;
  21454. },
  21455. enumerable: true,
  21456. configurable: true
  21457. });
  21458. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21459. get: function () {
  21460. if (this._texture) {
  21461. return this._texture._lodTextureMid;
  21462. }
  21463. return null;
  21464. },
  21465. enumerable: true,
  21466. configurable: true
  21467. });
  21468. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21469. get: function () {
  21470. if (this._texture) {
  21471. return this._texture._lodTextureLow;
  21472. }
  21473. return null;
  21474. },
  21475. enumerable: true,
  21476. configurable: true
  21477. });
  21478. BaseTexture.prototype.dispose = function () {
  21479. if (!this._scene) {
  21480. return;
  21481. }
  21482. // Animations
  21483. this._scene.stopAnimation(this);
  21484. // Remove from scene
  21485. this._scene._removePendingData(this);
  21486. var index = this._scene.textures.indexOf(this);
  21487. if (index >= 0) {
  21488. this._scene.textures.splice(index, 1);
  21489. }
  21490. if (this._texture === undefined) {
  21491. return;
  21492. }
  21493. // Release
  21494. this.releaseInternalTexture();
  21495. // Callback
  21496. this.onDisposeObservable.notifyObservers(this);
  21497. this.onDisposeObservable.clear();
  21498. };
  21499. BaseTexture.prototype.serialize = function () {
  21500. if (!this.name) {
  21501. return null;
  21502. }
  21503. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21504. // Animations
  21505. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21506. return serializationObject;
  21507. };
  21508. BaseTexture.WhenAllReady = function (textures, callback) {
  21509. var numRemaining = textures.length;
  21510. if (numRemaining === 0) {
  21511. callback();
  21512. return;
  21513. }
  21514. var _loop_1 = function () {
  21515. texture = textures[i];
  21516. if (texture.isReady()) {
  21517. if (--numRemaining === 0) {
  21518. callback();
  21519. }
  21520. }
  21521. else {
  21522. onLoadObservable = texture.onLoadObservable;
  21523. var onLoadCallback_1 = function () {
  21524. onLoadObservable.removeCallback(onLoadCallback_1);
  21525. if (--numRemaining === 0) {
  21526. callback();
  21527. }
  21528. };
  21529. onLoadObservable.add(onLoadCallback_1);
  21530. }
  21531. };
  21532. var texture, onLoadObservable;
  21533. for (var i = 0; i < textures.length; i++) {
  21534. _loop_1();
  21535. }
  21536. };
  21537. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21538. __decorate([
  21539. BABYLON.serialize()
  21540. ], BaseTexture.prototype, "name", void 0);
  21541. __decorate([
  21542. BABYLON.serialize("hasAlpha")
  21543. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21544. __decorate([
  21545. BABYLON.serialize()
  21546. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21547. __decorate([
  21548. BABYLON.serialize()
  21549. ], BaseTexture.prototype, "level", void 0);
  21550. __decorate([
  21551. BABYLON.serialize()
  21552. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21553. __decorate([
  21554. BABYLON.serialize("coordinatesMode")
  21555. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21556. __decorate([
  21557. BABYLON.serialize()
  21558. ], BaseTexture.prototype, "wrapU", void 0);
  21559. __decorate([
  21560. BABYLON.serialize()
  21561. ], BaseTexture.prototype, "wrapV", void 0);
  21562. __decorate([
  21563. BABYLON.serialize()
  21564. ], BaseTexture.prototype, "wrapR", void 0);
  21565. __decorate([
  21566. BABYLON.serialize()
  21567. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21568. __decorate([
  21569. BABYLON.serialize()
  21570. ], BaseTexture.prototype, "isCube", void 0);
  21571. __decorate([
  21572. BABYLON.serialize()
  21573. ], BaseTexture.prototype, "is3D", void 0);
  21574. __decorate([
  21575. BABYLON.serialize()
  21576. ], BaseTexture.prototype, "gammaSpace", void 0);
  21577. __decorate([
  21578. BABYLON.serialize()
  21579. ], BaseTexture.prototype, "invertZ", void 0);
  21580. __decorate([
  21581. BABYLON.serialize()
  21582. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21583. __decorate([
  21584. BABYLON.serialize()
  21585. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21586. __decorate([
  21587. BABYLON.serialize()
  21588. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21589. __decorate([
  21590. BABYLON.serialize()
  21591. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21592. return BaseTexture;
  21593. }());
  21594. BABYLON.BaseTexture = BaseTexture;
  21595. })(BABYLON || (BABYLON = {}));
  21596. //# sourceMappingURL=babylon.baseTexture.js.map
  21597. var BABYLON;
  21598. (function (BABYLON) {
  21599. var Texture = /** @class */ (function (_super) {
  21600. __extends(Texture, _super);
  21601. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21602. if (noMipmap === void 0) { noMipmap = false; }
  21603. if (invertY === void 0) { invertY = true; }
  21604. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21605. if (onLoad === void 0) { onLoad = null; }
  21606. if (onError === void 0) { onError = null; }
  21607. if (buffer === void 0) { buffer = null; }
  21608. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21609. var _this = _super.call(this, scene) || this;
  21610. _this.uOffset = 0;
  21611. _this.vOffset = 0;
  21612. _this.uScale = 1.0;
  21613. _this.vScale = 1.0;
  21614. _this.uAng = 0;
  21615. _this.vAng = 0;
  21616. _this.wAng = 0;
  21617. _this._isBlocking = true;
  21618. _this.name = url || "";
  21619. _this.url = url;
  21620. _this._noMipmap = noMipmap;
  21621. _this._invertY = invertY;
  21622. _this._samplingMode = samplingMode;
  21623. _this._buffer = buffer;
  21624. _this._deleteBuffer = deleteBuffer;
  21625. if (format) {
  21626. _this._format = format;
  21627. }
  21628. scene = _this.getScene();
  21629. if (!scene) {
  21630. return _this;
  21631. }
  21632. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21633. var load = function () {
  21634. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21635. _this.onLoadObservable.notifyObservers(_this);
  21636. }
  21637. if (onLoad) {
  21638. onLoad();
  21639. }
  21640. if (!_this.isBlocking && scene) {
  21641. scene.resetCachedMaterial();
  21642. }
  21643. };
  21644. if (!_this.url) {
  21645. _this._delayedOnLoad = load;
  21646. _this._delayedOnError = onError;
  21647. return _this;
  21648. }
  21649. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21650. if (!_this._texture) {
  21651. if (!scene.useDelayedTextureLoading) {
  21652. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21653. if (deleteBuffer) {
  21654. delete _this._buffer;
  21655. }
  21656. }
  21657. else {
  21658. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21659. _this._delayedOnLoad = load;
  21660. _this._delayedOnError = onError;
  21661. }
  21662. }
  21663. else {
  21664. if (_this._texture.isReady) {
  21665. BABYLON.Tools.SetImmediate(function () { return load(); });
  21666. }
  21667. else {
  21668. _this._texture.onLoadedObservable.add(load);
  21669. }
  21670. }
  21671. return _this;
  21672. }
  21673. Object.defineProperty(Texture.prototype, "noMipmap", {
  21674. get: function () {
  21675. return this._noMipmap;
  21676. },
  21677. enumerable: true,
  21678. configurable: true
  21679. });
  21680. Object.defineProperty(Texture.prototype, "isBlocking", {
  21681. get: function () {
  21682. return this._isBlocking;
  21683. },
  21684. set: function (value) {
  21685. this._isBlocking = value;
  21686. },
  21687. enumerable: true,
  21688. configurable: true
  21689. });
  21690. Object.defineProperty(Texture.prototype, "samplingMode", {
  21691. get: function () {
  21692. return this._samplingMode;
  21693. },
  21694. enumerable: true,
  21695. configurable: true
  21696. });
  21697. Texture.prototype.updateURL = function (url) {
  21698. this.url = url;
  21699. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21700. this.delayLoad();
  21701. };
  21702. Texture.prototype.delayLoad = function () {
  21703. var _this = this;
  21704. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21705. return;
  21706. }
  21707. var scene = this.getScene();
  21708. if (!scene) {
  21709. return;
  21710. }
  21711. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21712. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21713. if (!this._texture) {
  21714. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  21715. if (this._deleteBuffer) {
  21716. delete this._buffer;
  21717. }
  21718. }
  21719. else {
  21720. if (this._texture.isReady) {
  21721. BABYLON.Tools.SetImmediate(function () {
  21722. if (!_this._delayedOnLoad) {
  21723. return;
  21724. }
  21725. _this._delayedOnLoad();
  21726. });
  21727. }
  21728. else {
  21729. if (this._delayedOnLoad) {
  21730. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21731. }
  21732. }
  21733. }
  21734. };
  21735. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21736. if (!this._texture) {
  21737. return;
  21738. }
  21739. var scene = this.getScene();
  21740. if (!scene) {
  21741. return;
  21742. }
  21743. this._samplingMode = samplingMode;
  21744. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21745. };
  21746. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21747. x *= this.uScale;
  21748. y *= this.vScale;
  21749. x -= 0.5 * this.uScale;
  21750. y -= 0.5 * this.vScale;
  21751. z -= 0.5;
  21752. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21753. t.x += 0.5 * this.uScale + this.uOffset;
  21754. t.y += 0.5 * this.vScale + this.vOffset;
  21755. t.z += 0.5;
  21756. };
  21757. Texture.prototype.getTextureMatrix = function () {
  21758. var _this = this;
  21759. if (this.uOffset === this._cachedUOffset &&
  21760. this.vOffset === this._cachedVOffset &&
  21761. this.uScale === this._cachedUScale &&
  21762. this.vScale === this._cachedVScale &&
  21763. this.uAng === this._cachedUAng &&
  21764. this.vAng === this._cachedVAng &&
  21765. this.wAng === this._cachedWAng) {
  21766. return this._cachedTextureMatrix;
  21767. }
  21768. this._cachedUOffset = this.uOffset;
  21769. this._cachedVOffset = this.vOffset;
  21770. this._cachedUScale = this.uScale;
  21771. this._cachedVScale = this.vScale;
  21772. this._cachedUAng = this.uAng;
  21773. this._cachedVAng = this.vAng;
  21774. this._cachedWAng = this.wAng;
  21775. if (!this._cachedTextureMatrix) {
  21776. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21777. this._rowGenerationMatrix = new BABYLON.Matrix();
  21778. this._t0 = BABYLON.Vector3.Zero();
  21779. this._t1 = BABYLON.Vector3.Zero();
  21780. this._t2 = BABYLON.Vector3.Zero();
  21781. }
  21782. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21783. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21784. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21785. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21786. this._t1.subtractInPlace(this._t0);
  21787. this._t2.subtractInPlace(this._t0);
  21788. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21789. this._cachedTextureMatrix.m[0] = this._t1.x;
  21790. this._cachedTextureMatrix.m[1] = this._t1.y;
  21791. this._cachedTextureMatrix.m[2] = this._t1.z;
  21792. this._cachedTextureMatrix.m[4] = this._t2.x;
  21793. this._cachedTextureMatrix.m[5] = this._t2.y;
  21794. this._cachedTextureMatrix.m[6] = this._t2.z;
  21795. this._cachedTextureMatrix.m[8] = this._t0.x;
  21796. this._cachedTextureMatrix.m[9] = this._t0.y;
  21797. this._cachedTextureMatrix.m[10] = this._t0.z;
  21798. var scene = this.getScene();
  21799. if (!scene) {
  21800. return this._cachedTextureMatrix;
  21801. }
  21802. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21803. return mat.hasTexture(_this);
  21804. });
  21805. return this._cachedTextureMatrix;
  21806. };
  21807. Texture.prototype.getReflectionTextureMatrix = function () {
  21808. var _this = this;
  21809. var scene = this.getScene();
  21810. if (!scene) {
  21811. return this._cachedTextureMatrix;
  21812. }
  21813. if (this.uOffset === this._cachedUOffset &&
  21814. this.vOffset === this._cachedVOffset &&
  21815. this.uScale === this._cachedUScale &&
  21816. this.vScale === this._cachedVScale &&
  21817. this.coordinatesMode === this._cachedCoordinatesMode) {
  21818. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21819. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21820. return this._cachedTextureMatrix;
  21821. }
  21822. }
  21823. else {
  21824. return this._cachedTextureMatrix;
  21825. }
  21826. }
  21827. if (!this._cachedTextureMatrix) {
  21828. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21829. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21830. }
  21831. this._cachedUOffset = this.uOffset;
  21832. this._cachedVOffset = this.vOffset;
  21833. this._cachedUScale = this.uScale;
  21834. this._cachedVScale = this.vScale;
  21835. this._cachedCoordinatesMode = this.coordinatesMode;
  21836. switch (this.coordinatesMode) {
  21837. case Texture.PLANAR_MODE:
  21838. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21839. this._cachedTextureMatrix[0] = this.uScale;
  21840. this._cachedTextureMatrix[5] = this.vScale;
  21841. this._cachedTextureMatrix[12] = this.uOffset;
  21842. this._cachedTextureMatrix[13] = this.vOffset;
  21843. break;
  21844. case Texture.PROJECTION_MODE:
  21845. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21846. this._projectionModeMatrix.m[0] = 0.5;
  21847. this._projectionModeMatrix.m[5] = -0.5;
  21848. this._projectionModeMatrix.m[10] = 0.0;
  21849. this._projectionModeMatrix.m[12] = 0.5;
  21850. this._projectionModeMatrix.m[13] = 0.5;
  21851. this._projectionModeMatrix.m[14] = 1.0;
  21852. this._projectionModeMatrix.m[15] = 1.0;
  21853. var projectionMatrix = scene.getProjectionMatrix();
  21854. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21855. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21856. break;
  21857. default:
  21858. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21859. break;
  21860. }
  21861. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21862. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21863. });
  21864. return this._cachedTextureMatrix;
  21865. };
  21866. Texture.prototype.clone = function () {
  21867. var _this = this;
  21868. return BABYLON.SerializationHelper.Clone(function () {
  21869. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21870. }, this);
  21871. };
  21872. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21873. get: function () {
  21874. if (!this._onLoadObservable) {
  21875. this._onLoadObservable = new BABYLON.Observable();
  21876. }
  21877. return this._onLoadObservable;
  21878. },
  21879. enumerable: true,
  21880. configurable: true
  21881. });
  21882. Texture.prototype.serialize = function () {
  21883. var serializationObject = _super.prototype.serialize.call(this);
  21884. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21885. serializationObject.base64String = this._buffer;
  21886. serializationObject.name = serializationObject.name.replace("data:", "");
  21887. }
  21888. return serializationObject;
  21889. };
  21890. Texture.prototype.getClassName = function () {
  21891. return "Texture";
  21892. };
  21893. Texture.prototype.dispose = function () {
  21894. _super.prototype.dispose.call(this);
  21895. if (this.onLoadObservable) {
  21896. this.onLoadObservable.clear();
  21897. this._onLoadObservable = null;
  21898. }
  21899. this._delayedOnLoad = null;
  21900. this._delayedOnError = null;
  21901. };
  21902. // Statics
  21903. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21904. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21905. if (onLoad === void 0) { onLoad = null; }
  21906. if (onError === void 0) { onError = null; }
  21907. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21908. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21909. };
  21910. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21911. if (parsedTexture.customType) {
  21912. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21913. // Update Sampling Mode
  21914. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21915. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21916. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21917. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21918. }
  21919. }
  21920. return parsedCustomTexture;
  21921. }
  21922. if (parsedTexture.isCube) {
  21923. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21924. }
  21925. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21926. return null;
  21927. }
  21928. var texture = BABYLON.SerializationHelper.Parse(function () {
  21929. if (parsedTexture.mirrorPlane) {
  21930. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21931. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21932. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21933. return mirrorTexture;
  21934. }
  21935. else if (parsedTexture.isRenderTarget) {
  21936. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21937. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21938. return renderTargetTexture;
  21939. }
  21940. else {
  21941. var texture;
  21942. if (parsedTexture.base64String) {
  21943. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21944. }
  21945. else {
  21946. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21947. }
  21948. return texture;
  21949. }
  21950. }, parsedTexture, scene);
  21951. // Update Sampling Mode
  21952. if (parsedTexture.samplingMode) {
  21953. var sampling = parsedTexture.samplingMode;
  21954. if (texture._samplingMode !== sampling) {
  21955. texture.updateSamplingMode(sampling);
  21956. }
  21957. }
  21958. // Animations
  21959. if (parsedTexture.animations) {
  21960. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21961. var parsedAnimation = parsedTexture.animations[animationIndex];
  21962. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21963. }
  21964. }
  21965. return texture;
  21966. };
  21967. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21968. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21969. if (noMipmap === void 0) { noMipmap = false; }
  21970. if (invertY === void 0) { invertY = true; }
  21971. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21972. if (onLoad === void 0) { onLoad = null; }
  21973. if (onError === void 0) { onError = null; }
  21974. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21975. if (name.substr(0, 5) !== "data:") {
  21976. name = "data:" + name;
  21977. }
  21978. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21979. };
  21980. // Constants
  21981. Texture.NEAREST_SAMPLINGMODE = 1;
  21982. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21983. Texture.BILINEAR_SAMPLINGMODE = 2;
  21984. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21985. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21986. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21987. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21988. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21989. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21990. Texture.NEAREST_LINEAR = 7;
  21991. Texture.NEAREST_NEAREST = 8;
  21992. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21993. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21994. Texture.LINEAR_LINEAR = 11;
  21995. Texture.LINEAR_NEAREST = 12;
  21996. Texture.EXPLICIT_MODE = 0;
  21997. Texture.SPHERICAL_MODE = 1;
  21998. Texture.PLANAR_MODE = 2;
  21999. Texture.CUBIC_MODE = 3;
  22000. Texture.PROJECTION_MODE = 4;
  22001. Texture.SKYBOX_MODE = 5;
  22002. Texture.INVCUBIC_MODE = 6;
  22003. Texture.EQUIRECTANGULAR_MODE = 7;
  22004. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22005. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22006. Texture.CLAMP_ADDRESSMODE = 0;
  22007. Texture.WRAP_ADDRESSMODE = 1;
  22008. Texture.MIRROR_ADDRESSMODE = 2;
  22009. __decorate([
  22010. BABYLON.serialize()
  22011. ], Texture.prototype, "url", void 0);
  22012. __decorate([
  22013. BABYLON.serialize()
  22014. ], Texture.prototype, "uOffset", void 0);
  22015. __decorate([
  22016. BABYLON.serialize()
  22017. ], Texture.prototype, "vOffset", void 0);
  22018. __decorate([
  22019. BABYLON.serialize()
  22020. ], Texture.prototype, "uScale", void 0);
  22021. __decorate([
  22022. BABYLON.serialize()
  22023. ], Texture.prototype, "vScale", void 0);
  22024. __decorate([
  22025. BABYLON.serialize()
  22026. ], Texture.prototype, "uAng", void 0);
  22027. __decorate([
  22028. BABYLON.serialize()
  22029. ], Texture.prototype, "vAng", void 0);
  22030. __decorate([
  22031. BABYLON.serialize()
  22032. ], Texture.prototype, "wAng", void 0);
  22033. __decorate([
  22034. BABYLON.serialize()
  22035. ], Texture.prototype, "isBlocking", null);
  22036. return Texture;
  22037. }(BABYLON.BaseTexture));
  22038. BABYLON.Texture = Texture;
  22039. })(BABYLON || (BABYLON = {}));
  22040. //# sourceMappingURL=babylon.texture.js.map
  22041. var BABYLON;
  22042. (function (BABYLON) {
  22043. var _InstancesBatch = /** @class */ (function () {
  22044. function _InstancesBatch() {
  22045. this.mustReturn = false;
  22046. this.visibleInstances = new Array();
  22047. this.renderSelf = new Array();
  22048. }
  22049. return _InstancesBatch;
  22050. }());
  22051. BABYLON._InstancesBatch = _InstancesBatch;
  22052. var Mesh = /** @class */ (function (_super) {
  22053. __extends(Mesh, _super);
  22054. /**
  22055. * @constructor
  22056. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22057. * @param {Scene} scene The scene to add this mesh to.
  22058. * @param {Node} parent The parent of this mesh, if it has one
  22059. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22060. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22061. * When false, achieved by calling a clone(), also passing False.
  22062. * This will make creation of children, recursive.
  22063. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22064. */
  22065. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22066. if (scene === void 0) { scene = null; }
  22067. if (parent === void 0) { parent = null; }
  22068. if (source === void 0) { source = null; }
  22069. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22070. var _this = _super.call(this, name, scene) || this;
  22071. // Events
  22072. /**
  22073. * An event triggered before rendering the mesh
  22074. * @type {BABYLON.Observable}
  22075. */
  22076. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22077. /**
  22078. * An event triggered after rendering the mesh
  22079. * @type {BABYLON.Observable}
  22080. */
  22081. _this.onAfterRenderObservable = new BABYLON.Observable();
  22082. /**
  22083. * An event triggered before drawing the mesh
  22084. * @type {BABYLON.Observable}
  22085. */
  22086. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22087. // Members
  22088. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22089. _this.instances = new Array();
  22090. _this._LODLevels = new Array();
  22091. _this._visibleInstances = {};
  22092. _this._renderIdForInstances = new Array();
  22093. _this._batchCache = new _InstancesBatch();
  22094. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22095. // Use by builder only to know what orientation were the mesh build in.
  22096. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22097. _this.overrideMaterialSideOrientation = null;
  22098. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22099. // Will be used to save a source mesh reference, If any
  22100. _this._source = null;
  22101. scene = _this.getScene();
  22102. if (source) {
  22103. // Source mesh
  22104. _this._source = source;
  22105. // Geometry
  22106. if (source._geometry) {
  22107. source._geometry.applyToMesh(_this);
  22108. }
  22109. // Deep copy
  22110. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  22111. // Tags
  22112. if (BABYLON.Tags.HasTags(source)) {
  22113. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22114. }
  22115. // Parent
  22116. _this.parent = source.parent;
  22117. // Pivot
  22118. _this.setPivotMatrix(source.getPivotMatrix());
  22119. _this.id = name + "." + source.id;
  22120. // Material
  22121. _this.material = source.material;
  22122. var index;
  22123. if (!doNotCloneChildren) {
  22124. // Children
  22125. for (index = 0; index < scene.meshes.length; index++) {
  22126. var mesh = scene.meshes[index];
  22127. if (mesh.parent === source) {
  22128. // doNotCloneChildren is always going to be False
  22129. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22130. }
  22131. }
  22132. }
  22133. // Physics clone
  22134. var physicsEngine = _this.getScene().getPhysicsEngine();
  22135. if (clonePhysicsImpostor && physicsEngine) {
  22136. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22137. if (impostor) {
  22138. _this.physicsImpostor = impostor.clone(_this);
  22139. }
  22140. }
  22141. // Particles
  22142. for (index = 0; index < scene.particleSystems.length; index++) {
  22143. var system = scene.particleSystems[index];
  22144. if (system.emitter === source) {
  22145. system.clone(system.name, _this);
  22146. }
  22147. }
  22148. _this.computeWorldMatrix(true);
  22149. }
  22150. // Parent
  22151. if (parent !== null) {
  22152. _this.parent = parent;
  22153. }
  22154. return _this;
  22155. }
  22156. Object.defineProperty(Mesh, "FRONTSIDE", {
  22157. /**
  22158. * Mesh side orientation : usually the external or front surface
  22159. */
  22160. get: function () {
  22161. return Mesh._FRONTSIDE;
  22162. },
  22163. enumerable: true,
  22164. configurable: true
  22165. });
  22166. Object.defineProperty(Mesh, "BACKSIDE", {
  22167. /**
  22168. * Mesh side orientation : usually the internal or back surface
  22169. */
  22170. get: function () {
  22171. return Mesh._BACKSIDE;
  22172. },
  22173. enumerable: true,
  22174. configurable: true
  22175. });
  22176. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22177. /**
  22178. * Mesh side orientation : both internal and external or front and back surfaces
  22179. */
  22180. get: function () {
  22181. return Mesh._DOUBLESIDE;
  22182. },
  22183. enumerable: true,
  22184. configurable: true
  22185. });
  22186. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22187. /**
  22188. * Mesh side orientation : by default, `FRONTSIDE`
  22189. */
  22190. get: function () {
  22191. return Mesh._DEFAULTSIDE;
  22192. },
  22193. enumerable: true,
  22194. configurable: true
  22195. });
  22196. Object.defineProperty(Mesh, "NO_CAP", {
  22197. /**
  22198. * Mesh cap setting : no cap
  22199. */
  22200. get: function () {
  22201. return Mesh._NO_CAP;
  22202. },
  22203. enumerable: true,
  22204. configurable: true
  22205. });
  22206. Object.defineProperty(Mesh, "CAP_START", {
  22207. /**
  22208. * Mesh cap setting : one cap at the beginning of the mesh
  22209. */
  22210. get: function () {
  22211. return Mesh._CAP_START;
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Object.defineProperty(Mesh, "CAP_END", {
  22217. /**
  22218. * Mesh cap setting : one cap at the end of the mesh
  22219. */
  22220. get: function () {
  22221. return Mesh._CAP_END;
  22222. },
  22223. enumerable: true,
  22224. configurable: true
  22225. });
  22226. Object.defineProperty(Mesh, "CAP_ALL", {
  22227. /**
  22228. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22229. */
  22230. get: function () {
  22231. return Mesh._CAP_ALL;
  22232. },
  22233. enumerable: true,
  22234. configurable: true
  22235. });
  22236. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22237. set: function (callback) {
  22238. if (this._onBeforeDrawObserver) {
  22239. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22240. }
  22241. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22242. },
  22243. enumerable: true,
  22244. configurable: true
  22245. });
  22246. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22247. get: function () {
  22248. return this._morphTargetManager;
  22249. },
  22250. set: function (value) {
  22251. if (this._morphTargetManager === value) {
  22252. return;
  22253. }
  22254. this._morphTargetManager = value;
  22255. this._syncGeometryWithMorphTargetManager();
  22256. },
  22257. enumerable: true,
  22258. configurable: true
  22259. });
  22260. Object.defineProperty(Mesh.prototype, "source", {
  22261. get: function () {
  22262. return this._source;
  22263. },
  22264. enumerable: true,
  22265. configurable: true
  22266. });
  22267. // Methods
  22268. /**
  22269. * Returns the string "Mesh".
  22270. */
  22271. Mesh.prototype.getClassName = function () {
  22272. return "Mesh";
  22273. };
  22274. /**
  22275. * Returns a string.
  22276. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22277. */
  22278. Mesh.prototype.toString = function (fullDetails) {
  22279. var ret = _super.prototype.toString.call(this, fullDetails);
  22280. ret += ", n vertices: " + this.getTotalVertices();
  22281. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22282. if (this.animations) {
  22283. for (var i = 0; i < this.animations.length; i++) {
  22284. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22285. }
  22286. }
  22287. if (fullDetails) {
  22288. if (this._geometry) {
  22289. var ib = this.getIndices();
  22290. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22291. if (vb && ib) {
  22292. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22293. }
  22294. }
  22295. else {
  22296. ret += ", flat shading: UNKNOWN";
  22297. }
  22298. }
  22299. return ret;
  22300. };
  22301. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22302. /**
  22303. * True if the mesh has some Levels Of Details (LOD).
  22304. * Returns a boolean.
  22305. */
  22306. get: function () {
  22307. return this._LODLevels.length > 0;
  22308. },
  22309. enumerable: true,
  22310. configurable: true
  22311. });
  22312. Mesh.prototype._sortLODLevels = function () {
  22313. this._LODLevels.sort(function (a, b) {
  22314. if (a.distance < b.distance) {
  22315. return 1;
  22316. }
  22317. if (a.distance > b.distance) {
  22318. return -1;
  22319. }
  22320. return 0;
  22321. });
  22322. };
  22323. /**
  22324. * Add a mesh as LOD level triggered at the given distance.
  22325. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22326. * @param {number} distance The distance from the center of the object to show this level
  22327. * @param {Mesh} mesh The mesh to be added as LOD level
  22328. * @return {Mesh} This mesh (for chaining)
  22329. */
  22330. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22331. if (mesh && mesh._masterMesh) {
  22332. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22333. return this;
  22334. }
  22335. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22336. this._LODLevels.push(level);
  22337. if (mesh) {
  22338. mesh._masterMesh = this;
  22339. }
  22340. this._sortLODLevels();
  22341. return this;
  22342. };
  22343. /**
  22344. * Returns the LOD level mesh at the passed distance or null if not found.
  22345. * It is related to the method `addLODLevel(distance, mesh)`.
  22346. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22347. * Returns an object Mesh or `null`.
  22348. */
  22349. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22350. for (var index = 0; index < this._LODLevels.length; index++) {
  22351. var level = this._LODLevels[index];
  22352. if (level.distance === distance) {
  22353. return level.mesh;
  22354. }
  22355. }
  22356. return null;
  22357. };
  22358. /**
  22359. * Remove a mesh from the LOD array
  22360. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22361. * @param {Mesh} mesh The mesh to be removed.
  22362. * @return {Mesh} This mesh (for chaining)
  22363. */
  22364. Mesh.prototype.removeLODLevel = function (mesh) {
  22365. for (var index = 0; index < this._LODLevels.length; index++) {
  22366. if (this._LODLevels[index].mesh === mesh) {
  22367. this._LODLevels.splice(index, 1);
  22368. if (mesh) {
  22369. mesh._masterMesh = null;
  22370. }
  22371. }
  22372. }
  22373. this._sortLODLevels();
  22374. return this;
  22375. };
  22376. /**
  22377. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22378. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22379. */
  22380. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22381. if (!this._LODLevels || this._LODLevels.length === 0) {
  22382. return this;
  22383. }
  22384. var bSphere;
  22385. if (boundingSphere) {
  22386. bSphere = boundingSphere;
  22387. }
  22388. else {
  22389. var boundingInfo = this.getBoundingInfo();
  22390. if (!boundingInfo) {
  22391. return this;
  22392. }
  22393. bSphere = boundingInfo.boundingSphere;
  22394. }
  22395. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22396. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22397. if (this.onLODLevelSelection) {
  22398. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22399. }
  22400. return this;
  22401. }
  22402. for (var index = 0; index < this._LODLevels.length; index++) {
  22403. var level = this._LODLevels[index];
  22404. if (level.distance < distanceToCamera) {
  22405. if (level.mesh) {
  22406. level.mesh._preActivate();
  22407. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22408. }
  22409. if (this.onLODLevelSelection) {
  22410. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22411. }
  22412. return level.mesh;
  22413. }
  22414. }
  22415. if (this.onLODLevelSelection) {
  22416. this.onLODLevelSelection(distanceToCamera, this, this);
  22417. }
  22418. return this;
  22419. };
  22420. Object.defineProperty(Mesh.prototype, "geometry", {
  22421. /**
  22422. * Returns the mesh internal Geometry object.
  22423. */
  22424. get: function () {
  22425. return this._geometry;
  22426. },
  22427. enumerable: true,
  22428. configurable: true
  22429. });
  22430. /**
  22431. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22432. */
  22433. Mesh.prototype.getTotalVertices = function () {
  22434. if (!this._geometry) {
  22435. return 0;
  22436. }
  22437. return this._geometry.getTotalVertices();
  22438. };
  22439. /**
  22440. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22441. * 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.
  22442. * You can force the copy with forceCopy === true
  22443. * Returns null if the mesh has no geometry or no vertex buffer.
  22444. * Possible `kind` values :
  22445. * - BABYLON.VertexBuffer.PositionKind
  22446. * - BABYLON.VertexBuffer.UVKind
  22447. * - BABYLON.VertexBuffer.UV2Kind
  22448. * - BABYLON.VertexBuffer.UV3Kind
  22449. * - BABYLON.VertexBuffer.UV4Kind
  22450. * - BABYLON.VertexBuffer.UV5Kind
  22451. * - BABYLON.VertexBuffer.UV6Kind
  22452. * - BABYLON.VertexBuffer.ColorKind
  22453. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22454. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22455. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22456. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22457. */
  22458. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22459. if (!this._geometry) {
  22460. return null;
  22461. }
  22462. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22463. };
  22464. /**
  22465. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22466. * Returns `null` if the mesh has no geometry.
  22467. * Possible `kind` values :
  22468. * - BABYLON.VertexBuffer.PositionKind
  22469. * - BABYLON.VertexBuffer.UVKind
  22470. * - BABYLON.VertexBuffer.UV2Kind
  22471. * - BABYLON.VertexBuffer.UV3Kind
  22472. * - BABYLON.VertexBuffer.UV4Kind
  22473. * - BABYLON.VertexBuffer.UV5Kind
  22474. * - BABYLON.VertexBuffer.UV6Kind
  22475. * - BABYLON.VertexBuffer.ColorKind
  22476. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22477. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22478. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22479. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22480. */
  22481. Mesh.prototype.getVertexBuffer = function (kind) {
  22482. if (!this._geometry) {
  22483. return null;
  22484. }
  22485. return this._geometry.getVertexBuffer(kind);
  22486. };
  22487. /**
  22488. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22489. * Possible `kind` values :
  22490. * - BABYLON.VertexBuffer.PositionKind
  22491. * - BABYLON.VertexBuffer.UVKind
  22492. * - BABYLON.VertexBuffer.UV2Kind
  22493. * - BABYLON.VertexBuffer.UV3Kind
  22494. * - BABYLON.VertexBuffer.UV4Kind
  22495. * - BABYLON.VertexBuffer.UV5Kind
  22496. * - BABYLON.VertexBuffer.UV6Kind
  22497. * - BABYLON.VertexBuffer.ColorKind
  22498. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22499. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22500. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22501. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22502. */
  22503. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22504. if (!this._geometry) {
  22505. if (this._delayInfo) {
  22506. return this._delayInfo.indexOf(kind) !== -1;
  22507. }
  22508. return false;
  22509. }
  22510. return this._geometry.isVerticesDataPresent(kind);
  22511. };
  22512. /**
  22513. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22514. * Possible `kind` values :
  22515. * - BABYLON.VertexBuffer.PositionKind
  22516. * - BABYLON.VertexBuffer.UVKind
  22517. * - BABYLON.VertexBuffer.UV2Kind
  22518. * - BABYLON.VertexBuffer.UV3Kind
  22519. * - BABYLON.VertexBuffer.UV4Kind
  22520. * - BABYLON.VertexBuffer.UV5Kind
  22521. * - BABYLON.VertexBuffer.UV6Kind
  22522. * - BABYLON.VertexBuffer.ColorKind
  22523. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22524. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22525. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22526. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22527. */
  22528. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22529. if (!this._geometry) {
  22530. if (this._delayInfo) {
  22531. return this._delayInfo.indexOf(kind) !== -1;
  22532. }
  22533. return false;
  22534. }
  22535. return this._geometry.isVertexBufferUpdatable(kind);
  22536. };
  22537. /**
  22538. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22539. * Possible `kind` values :
  22540. * - BABYLON.VertexBuffer.PositionKind
  22541. * - BABYLON.VertexBuffer.UVKind
  22542. * - BABYLON.VertexBuffer.UV2Kind
  22543. * - BABYLON.VertexBuffer.UV3Kind
  22544. * - BABYLON.VertexBuffer.UV4Kind
  22545. * - BABYLON.VertexBuffer.UV5Kind
  22546. * - BABYLON.VertexBuffer.UV6Kind
  22547. * - BABYLON.VertexBuffer.ColorKind
  22548. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22549. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22550. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22551. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22552. */
  22553. Mesh.prototype.getVerticesDataKinds = function () {
  22554. if (!this._geometry) {
  22555. var result = new Array();
  22556. if (this._delayInfo) {
  22557. this._delayInfo.forEach(function (kind, index, array) {
  22558. result.push(kind);
  22559. });
  22560. }
  22561. return result;
  22562. }
  22563. return this._geometry.getVerticesDataKinds();
  22564. };
  22565. /**
  22566. * Returns a positive integer : the total number of indices in this mesh geometry.
  22567. * Returns zero if the mesh has no geometry.
  22568. */
  22569. Mesh.prototype.getTotalIndices = function () {
  22570. if (!this._geometry) {
  22571. return 0;
  22572. }
  22573. return this._geometry.getTotalIndices();
  22574. };
  22575. /**
  22576. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22577. * 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.
  22578. * Returns an empty array if the mesh has no geometry.
  22579. */
  22580. Mesh.prototype.getIndices = function (copyWhenShared) {
  22581. if (!this._geometry) {
  22582. return [];
  22583. }
  22584. return this._geometry.getIndices(copyWhenShared);
  22585. };
  22586. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22587. get: function () {
  22588. return this._masterMesh !== null && this._masterMesh !== undefined;
  22589. },
  22590. enumerable: true,
  22591. configurable: true
  22592. });
  22593. /**
  22594. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22595. */
  22596. Mesh.prototype.isReady = function () {
  22597. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22598. return false;
  22599. }
  22600. return _super.prototype.isReady.call(this);
  22601. };
  22602. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22603. /**
  22604. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22605. * This property is pertinent only for updatable parametric shapes.
  22606. */
  22607. get: function () {
  22608. return this._areNormalsFrozen;
  22609. },
  22610. enumerable: true,
  22611. configurable: true
  22612. });
  22613. /**
  22614. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22615. * It has no effect at all on other shapes.
  22616. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22617. * Returns the Mesh.
  22618. */
  22619. Mesh.prototype.freezeNormals = function () {
  22620. this._areNormalsFrozen = true;
  22621. return this;
  22622. };
  22623. /**
  22624. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22625. * It has no effect at all on other shapes.
  22626. * It reactivates the mesh normals computation if it was previously frozen.
  22627. * Returns the Mesh.
  22628. */
  22629. Mesh.prototype.unfreezeNormals = function () {
  22630. this._areNormalsFrozen = false;
  22631. return this;
  22632. };
  22633. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22634. /**
  22635. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22636. */
  22637. set: function (count) {
  22638. this._overridenInstanceCount = count;
  22639. },
  22640. enumerable: true,
  22641. configurable: true
  22642. });
  22643. // Methods
  22644. Mesh.prototype._preActivate = function () {
  22645. var sceneRenderId = this.getScene().getRenderId();
  22646. if (this._preActivateId === sceneRenderId) {
  22647. return this;
  22648. }
  22649. this._preActivateId = sceneRenderId;
  22650. this._visibleInstances = null;
  22651. return this;
  22652. };
  22653. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22654. if (this._visibleInstances) {
  22655. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22656. }
  22657. return this;
  22658. };
  22659. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22660. if (!this._visibleInstances) {
  22661. this._visibleInstances = {};
  22662. this._visibleInstances.defaultRenderId = renderId;
  22663. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22664. }
  22665. if (!this._visibleInstances[renderId]) {
  22666. this._visibleInstances[renderId] = new Array();
  22667. }
  22668. this._visibleInstances[renderId].push(instance);
  22669. return this;
  22670. };
  22671. /**
  22672. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22673. * This means the mesh underlying bounding box and sphere are recomputed.
  22674. * Returns the Mesh.
  22675. */
  22676. Mesh.prototype.refreshBoundingInfo = function () {
  22677. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22678. return this;
  22679. }
  22680. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22681. if (data) {
  22682. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22683. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22684. }
  22685. if (this.subMeshes) {
  22686. for (var index = 0; index < this.subMeshes.length; index++) {
  22687. this.subMeshes[index].refreshBoundingInfo();
  22688. }
  22689. }
  22690. this._updateBoundingInfo();
  22691. return this;
  22692. };
  22693. Mesh.prototype._createGlobalSubMesh = function (force) {
  22694. var totalVertices = this.getTotalVertices();
  22695. if (!totalVertices || !this.getIndices()) {
  22696. return null;
  22697. }
  22698. // Check if we need to recreate the submeshes
  22699. if (this.subMeshes && this.subMeshes.length > 0) {
  22700. var ib = this.getIndices();
  22701. if (!ib) {
  22702. return null;
  22703. }
  22704. var totalIndices = ib.length;
  22705. var needToRecreate = false;
  22706. if (force) {
  22707. needToRecreate = true;
  22708. }
  22709. else {
  22710. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  22711. var submesh = _a[_i];
  22712. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  22713. needToRecreate = true;
  22714. break;
  22715. }
  22716. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  22717. needToRecreate = true;
  22718. break;
  22719. }
  22720. }
  22721. }
  22722. if (!needToRecreate) {
  22723. return this.subMeshes[0];
  22724. }
  22725. }
  22726. this.releaseSubMeshes();
  22727. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22728. };
  22729. Mesh.prototype.subdivide = function (count) {
  22730. if (count < 1) {
  22731. return;
  22732. }
  22733. var totalIndices = this.getTotalIndices();
  22734. var subdivisionSize = (totalIndices / count) | 0;
  22735. var offset = 0;
  22736. // Ensure that subdivisionSize is a multiple of 3
  22737. while (subdivisionSize % 3 !== 0) {
  22738. subdivisionSize++;
  22739. }
  22740. this.releaseSubMeshes();
  22741. for (var index = 0; index < count; index++) {
  22742. if (offset >= totalIndices) {
  22743. break;
  22744. }
  22745. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22746. offset += subdivisionSize;
  22747. }
  22748. this.synchronizeInstances();
  22749. };
  22750. /**
  22751. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22752. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22753. * The `data` are either a numeric array either a Float32Array.
  22754. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22755. * 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).
  22756. * Note that a new underlying VertexBuffer object is created each call.
  22757. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22758. *
  22759. * Possible `kind` values :
  22760. * - BABYLON.VertexBuffer.PositionKind
  22761. * - BABYLON.VertexBuffer.UVKind
  22762. * - BABYLON.VertexBuffer.UV2Kind
  22763. * - BABYLON.VertexBuffer.UV3Kind
  22764. * - BABYLON.VertexBuffer.UV4Kind
  22765. * - BABYLON.VertexBuffer.UV5Kind
  22766. * - BABYLON.VertexBuffer.UV6Kind
  22767. * - BABYLON.VertexBuffer.ColorKind
  22768. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22769. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22770. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22771. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22772. *
  22773. * Returns the Mesh.
  22774. */
  22775. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22776. if (updatable === void 0) { updatable = false; }
  22777. if (!this._geometry) {
  22778. var vertexData = new BABYLON.VertexData();
  22779. vertexData.set(data, kind);
  22780. var scene = this.getScene();
  22781. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22782. }
  22783. else {
  22784. this._geometry.setVerticesData(kind, data, updatable, stride);
  22785. }
  22786. return this;
  22787. };
  22788. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22789. if (updatable === void 0) { updatable = true; }
  22790. var vb = this.getVertexBuffer(kind);
  22791. if (!vb || vb.isUpdatable() === updatable) {
  22792. return;
  22793. }
  22794. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22795. };
  22796. /**
  22797. * Sets the mesh VertexBuffer.
  22798. * Returns the Mesh.
  22799. */
  22800. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22801. if (!this._geometry) {
  22802. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  22803. }
  22804. this._geometry.setVerticesBuffer(buffer);
  22805. return this;
  22806. };
  22807. /**
  22808. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22809. * If the mesh has no geometry, it is simply returned as it is.
  22810. * The `data` are either a numeric array either a Float32Array.
  22811. * No new underlying VertexBuffer object is created.
  22812. * 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.
  22813. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22814. *
  22815. * Possible `kind` values :
  22816. * - BABYLON.VertexBuffer.PositionKind
  22817. * - BABYLON.VertexBuffer.UVKind
  22818. * - BABYLON.VertexBuffer.UV2Kind
  22819. * - BABYLON.VertexBuffer.UV3Kind
  22820. * - BABYLON.VertexBuffer.UV4Kind
  22821. * - BABYLON.VertexBuffer.UV5Kind
  22822. * - BABYLON.VertexBuffer.UV6Kind
  22823. * - BABYLON.VertexBuffer.ColorKind
  22824. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22825. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22826. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22827. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22828. *
  22829. * Returns the Mesh.
  22830. */
  22831. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22832. if (!this._geometry) {
  22833. return this;
  22834. }
  22835. if (!makeItUnique) {
  22836. this._geometry.updateVerticesData(kind, data, updateExtends);
  22837. }
  22838. else {
  22839. this.makeGeometryUnique();
  22840. this.updateVerticesData(kind, data, updateExtends, false);
  22841. }
  22842. return this;
  22843. };
  22844. /**
  22845. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22846. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22847. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22848. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22849. * Returns the Mesh.
  22850. */
  22851. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22852. if (computeNormals === void 0) { computeNormals = true; }
  22853. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22854. if (!positions) {
  22855. return this;
  22856. }
  22857. positionFunction(positions);
  22858. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22859. if (computeNormals) {
  22860. var indices = this.getIndices();
  22861. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22862. if (!normals) {
  22863. return this;
  22864. }
  22865. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22866. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22867. }
  22868. return this;
  22869. };
  22870. /**
  22871. * Creates a un-shared specific occurence of the geometry for the mesh.
  22872. * Returns the Mesh.
  22873. */
  22874. Mesh.prototype.makeGeometryUnique = function () {
  22875. if (!this._geometry) {
  22876. return this;
  22877. }
  22878. var oldGeometry = this._geometry;
  22879. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22880. oldGeometry.releaseForMesh(this, true);
  22881. geometry.applyToMesh(this);
  22882. return this;
  22883. };
  22884. /**
  22885. * Sets the mesh indices.
  22886. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22887. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22888. * This method creates a new index buffer each call.
  22889. * Returns the Mesh.
  22890. */
  22891. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  22892. if (totalVertices === void 0) { totalVertices = null; }
  22893. if (updatable === void 0) { updatable = false; }
  22894. if (!this._geometry) {
  22895. var vertexData = new BABYLON.VertexData();
  22896. vertexData.indices = indices;
  22897. var scene = this.getScene();
  22898. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22899. }
  22900. else {
  22901. this._geometry.setIndices(indices, totalVertices, updatable);
  22902. }
  22903. return this;
  22904. };
  22905. /**
  22906. * Update the current index buffer
  22907. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  22908. * Returns the Mesh.
  22909. */
  22910. Mesh.prototype.updateIndices = function (indices, offset) {
  22911. if (!this._geometry) {
  22912. return this;
  22913. }
  22914. this._geometry.updateIndices(indices, offset);
  22915. return this;
  22916. };
  22917. /**
  22918. * Invert the geometry to move from a right handed system to a left handed one.
  22919. * Returns the Mesh.
  22920. */
  22921. Mesh.prototype.toLeftHanded = function () {
  22922. if (!this._geometry) {
  22923. return this;
  22924. }
  22925. this._geometry.toLeftHanded();
  22926. return this;
  22927. };
  22928. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22929. if (!this._geometry) {
  22930. return this;
  22931. }
  22932. var engine = this.getScene().getEngine();
  22933. // Wireframe
  22934. var indexToBind;
  22935. if (this._unIndexed) {
  22936. indexToBind = null;
  22937. }
  22938. else {
  22939. switch (fillMode) {
  22940. case BABYLON.Material.PointFillMode:
  22941. indexToBind = null;
  22942. break;
  22943. case BABYLON.Material.WireFrameFillMode:
  22944. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22945. break;
  22946. default:
  22947. case BABYLON.Material.TriangleFillMode:
  22948. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22949. break;
  22950. }
  22951. }
  22952. // VBOs
  22953. this._geometry._bind(effect, indexToBind);
  22954. return this;
  22955. };
  22956. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22957. if (alternate === void 0) { alternate = false; }
  22958. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22959. return this;
  22960. }
  22961. this.onBeforeDrawObservable.notifyObservers(this);
  22962. var scene = this.getScene();
  22963. var engine = scene.getEngine();
  22964. // Draw order
  22965. switch (fillMode) {
  22966. case BABYLON.Material.PointFillMode:
  22967. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22968. break;
  22969. case BABYLON.Material.WireFrameFillMode:
  22970. if (this._unIndexed) {
  22971. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22972. }
  22973. else {
  22974. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22975. }
  22976. break;
  22977. default:
  22978. if (this._unIndexed) {
  22979. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22980. }
  22981. else {
  22982. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22983. }
  22984. }
  22985. if (scene._isAlternateRenderingEnabled && !alternate) {
  22986. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22987. if (!effect || !scene.activeCamera) {
  22988. return this;
  22989. }
  22990. scene._switchToAlternateCameraConfiguration(true);
  22991. this._effectiveMaterial.bindView(effect);
  22992. this._effectiveMaterial.bindViewProjection(effect);
  22993. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22994. this._draw(subMesh, fillMode, instancesCount, true);
  22995. engine.setViewport(scene.activeCamera.viewport);
  22996. scene._switchToAlternateCameraConfiguration(false);
  22997. this._effectiveMaterial.bindView(effect);
  22998. this._effectiveMaterial.bindViewProjection(effect);
  22999. }
  23000. return this;
  23001. };
  23002. /**
  23003. * Registers for this mesh a javascript function called just before the rendering process.
  23004. * This function is passed the current mesh.
  23005. * Return the Mesh.
  23006. */
  23007. Mesh.prototype.registerBeforeRender = function (func) {
  23008. this.onBeforeRenderObservable.add(func);
  23009. return this;
  23010. };
  23011. /**
  23012. * Disposes a previously registered javascript function called before the rendering.
  23013. * This function is passed the current mesh.
  23014. * Returns the Mesh.
  23015. */
  23016. Mesh.prototype.unregisterBeforeRender = function (func) {
  23017. this.onBeforeRenderObservable.removeCallback(func);
  23018. return this;
  23019. };
  23020. /**
  23021. * Registers for this mesh a javascript function called just after the rendering is complete.
  23022. * This function is passed the current mesh.
  23023. * Returns the Mesh.
  23024. */
  23025. Mesh.prototype.registerAfterRender = function (func) {
  23026. this.onAfterRenderObservable.add(func);
  23027. return this;
  23028. };
  23029. /**
  23030. * Disposes a previously registered javascript function called after the rendering.
  23031. * This function is passed the current mesh.
  23032. * Return the Mesh.
  23033. */
  23034. Mesh.prototype.unregisterAfterRender = function (func) {
  23035. this.onAfterRenderObservable.removeCallback(func);
  23036. return this;
  23037. };
  23038. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23039. var scene = this.getScene();
  23040. this._batchCache.mustReturn = false;
  23041. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23042. this._batchCache.visibleInstances[subMeshId] = null;
  23043. if (this._visibleInstances) {
  23044. var currentRenderId = scene.getRenderId();
  23045. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23046. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23047. var selfRenderId = this._renderId;
  23048. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23049. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23050. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23051. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23052. }
  23053. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23054. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23055. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23056. this._batchCache.mustReturn = true;
  23057. return this._batchCache;
  23058. }
  23059. if (currentRenderId !== selfRenderId) {
  23060. this._batchCache.renderSelf[subMeshId] = false;
  23061. }
  23062. }
  23063. this._renderIdForInstances[subMeshId] = currentRenderId;
  23064. }
  23065. return this._batchCache;
  23066. };
  23067. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23068. var visibleInstances = batch.visibleInstances[subMesh._id];
  23069. if (!visibleInstances) {
  23070. return this;
  23071. }
  23072. var matricesCount = visibleInstances.length + 1;
  23073. var bufferSize = matricesCount * 16 * 4;
  23074. var currentInstancesBufferSize = this._instancesBufferSize;
  23075. var instancesBuffer = this._instancesBuffer;
  23076. while (this._instancesBufferSize < bufferSize) {
  23077. this._instancesBufferSize *= 2;
  23078. }
  23079. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23080. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23081. }
  23082. var offset = 0;
  23083. var instancesCount = 0;
  23084. var world = this.getWorldMatrix();
  23085. if (batch.renderSelf[subMesh._id]) {
  23086. world.copyToArray(this._instancesData, offset);
  23087. offset += 16;
  23088. instancesCount++;
  23089. }
  23090. if (visibleInstances) {
  23091. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23092. var instance = visibleInstances[instanceIndex];
  23093. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23094. offset += 16;
  23095. instancesCount++;
  23096. }
  23097. }
  23098. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23099. if (instancesBuffer) {
  23100. instancesBuffer.dispose();
  23101. }
  23102. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23103. this._instancesBuffer = instancesBuffer;
  23104. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23105. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23106. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23107. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23108. }
  23109. else {
  23110. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23111. }
  23112. this._bind(subMesh, effect, fillMode);
  23113. this._draw(subMesh, fillMode, instancesCount);
  23114. engine.unbindInstanceAttributes();
  23115. return this;
  23116. };
  23117. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23118. var scene = this.getScene();
  23119. var engine = scene.getEngine();
  23120. if (hardwareInstancedRendering) {
  23121. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23122. }
  23123. else {
  23124. if (batch.renderSelf[subMesh._id]) {
  23125. // Draw
  23126. if (onBeforeDraw) {
  23127. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23128. }
  23129. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23130. }
  23131. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23132. if (visibleInstancesForSubMesh) {
  23133. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23134. var instance = visibleInstancesForSubMesh[instanceIndex];
  23135. // World
  23136. var world = instance.getWorldMatrix();
  23137. if (onBeforeDraw) {
  23138. onBeforeDraw(true, world, effectiveMaterial);
  23139. }
  23140. // Draw
  23141. this._draw(subMesh, fillMode);
  23142. }
  23143. }
  23144. }
  23145. return this;
  23146. };
  23147. /**
  23148. * Triggers the draw call for the mesh.
  23149. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23150. * Returns the Mesh.
  23151. */
  23152. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23153. this.checkOcclusionQuery();
  23154. if (this._isOccluded) {
  23155. return this;
  23156. }
  23157. var scene = this.getScene();
  23158. // Managing instances
  23159. var batch = this._getInstancesRenderList(subMesh._id);
  23160. if (batch.mustReturn) {
  23161. return this;
  23162. }
  23163. // Checking geometry state
  23164. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23165. return this;
  23166. }
  23167. this.onBeforeRenderObservable.notifyObservers(this);
  23168. var engine = scene.getEngine();
  23169. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23170. // Material
  23171. var material = subMesh.getMaterial();
  23172. if (!material) {
  23173. return this;
  23174. }
  23175. this._effectiveMaterial = material;
  23176. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23177. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23178. return this;
  23179. }
  23180. }
  23181. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23182. return this;
  23183. }
  23184. // Alpha mode
  23185. if (enableAlphaMode) {
  23186. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23187. }
  23188. // Outline - step 1
  23189. var savedDepthWrite = engine.getDepthWrite();
  23190. if (this.renderOutline) {
  23191. engine.setDepthWrite(false);
  23192. scene.getOutlineRenderer().render(subMesh, batch);
  23193. engine.setDepthWrite(savedDepthWrite);
  23194. }
  23195. var effect;
  23196. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23197. effect = subMesh.effect;
  23198. }
  23199. else {
  23200. effect = this._effectiveMaterial.getEffect();
  23201. }
  23202. if (!effect) {
  23203. return this;
  23204. }
  23205. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23206. if (this._effectiveMaterial.forceDepthWrite) {
  23207. engine.setDepthWrite(true);
  23208. }
  23209. // Bind
  23210. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23211. if (!hardwareInstancedRendering) {
  23212. this._bind(subMesh, effect, fillMode);
  23213. }
  23214. var world = this.getWorldMatrix();
  23215. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23216. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23217. }
  23218. else {
  23219. this._effectiveMaterial.bind(world, this);
  23220. }
  23221. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23222. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23223. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23224. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23225. }
  23226. // Draw
  23227. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23228. // Unbind
  23229. this._effectiveMaterial.unbind();
  23230. // Outline - step 2
  23231. if (this.renderOutline && savedDepthWrite) {
  23232. engine.setDepthWrite(true);
  23233. engine.setColorWrite(false);
  23234. scene.getOutlineRenderer().render(subMesh, batch);
  23235. engine.setColorWrite(true);
  23236. }
  23237. // Overlay
  23238. if (this.renderOverlay) {
  23239. var currentMode = engine.getAlphaMode();
  23240. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23241. scene.getOutlineRenderer().render(subMesh, batch, true);
  23242. engine.setAlphaMode(currentMode);
  23243. }
  23244. this.onAfterRenderObservable.notifyObservers(this);
  23245. return this;
  23246. };
  23247. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23248. if (isInstance) {
  23249. effectiveMaterial.bindOnlyWorldMatrix(world);
  23250. }
  23251. return this;
  23252. };
  23253. /**
  23254. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23255. */
  23256. Mesh.prototype.getEmittedParticleSystems = function () {
  23257. var results = new Array();
  23258. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23259. var particleSystem = this.getScene().particleSystems[index];
  23260. if (particleSystem.emitter === this) {
  23261. results.push(particleSystem);
  23262. }
  23263. }
  23264. return results;
  23265. };
  23266. /**
  23267. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23268. */
  23269. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23270. var results = new Array();
  23271. var descendants = this.getDescendants();
  23272. descendants.push(this);
  23273. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23274. var particleSystem = this.getScene().particleSystems[index];
  23275. var emitter = particleSystem.emitter;
  23276. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23277. results.push(particleSystem);
  23278. }
  23279. }
  23280. return results;
  23281. };
  23282. Mesh.prototype._checkDelayState = function () {
  23283. var scene = this.getScene();
  23284. if (this._geometry) {
  23285. this._geometry.load(scene);
  23286. }
  23287. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23288. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23289. this._queueLoad(this, scene);
  23290. }
  23291. return this;
  23292. };
  23293. Mesh.prototype._queueLoad = function (mesh, scene) {
  23294. var _this = this;
  23295. scene._addPendingData(mesh);
  23296. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23297. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23298. if (data instanceof ArrayBuffer) {
  23299. _this._delayLoadingFunction(data, _this);
  23300. }
  23301. else {
  23302. _this._delayLoadingFunction(JSON.parse(data), _this);
  23303. }
  23304. _this.instances.forEach(function (instance) {
  23305. instance._syncSubMeshes();
  23306. });
  23307. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23308. scene._removePendingData(_this);
  23309. }, function () { }, scene.database, getBinaryData);
  23310. return this;
  23311. };
  23312. /**
  23313. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23314. */
  23315. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23316. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23317. return false;
  23318. }
  23319. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23320. return false;
  23321. }
  23322. this._checkDelayState();
  23323. return true;
  23324. };
  23325. /**
  23326. * Sets the mesh material by the material or multiMaterial `id` property.
  23327. * The material `id` is a string identifying the material or the multiMaterial.
  23328. * This method returns the Mesh.
  23329. */
  23330. Mesh.prototype.setMaterialByID = function (id) {
  23331. var materials = this.getScene().materials;
  23332. var index;
  23333. for (index = materials.length - 1; index > -1; index--) {
  23334. if (materials[index].id === id) {
  23335. this.material = materials[index];
  23336. return this;
  23337. }
  23338. }
  23339. // Multi
  23340. var multiMaterials = this.getScene().multiMaterials;
  23341. for (index = multiMaterials.length - 1; index > -1; index--) {
  23342. if (multiMaterials[index].id === id) {
  23343. this.material = multiMaterials[index];
  23344. return this;
  23345. }
  23346. }
  23347. return this;
  23348. };
  23349. /**
  23350. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23351. */
  23352. Mesh.prototype.getAnimatables = function () {
  23353. var results = new Array();
  23354. if (this.material) {
  23355. results.push(this.material);
  23356. }
  23357. if (this.skeleton) {
  23358. results.push(this.skeleton);
  23359. }
  23360. return results;
  23361. };
  23362. /**
  23363. * Modifies the mesh geometry according to the passed transformation matrix.
  23364. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23365. * The mesh normals are modified accordingly the same transformation.
  23366. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23367. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23368. * Returns the Mesh.
  23369. */
  23370. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23371. // Position
  23372. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23373. return this;
  23374. }
  23375. var submeshes = this.subMeshes.splice(0);
  23376. this._resetPointsArrayCache();
  23377. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23378. var temp = new Array();
  23379. var index;
  23380. for (index = 0; index < data.length; index += 3) {
  23381. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23382. }
  23383. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23384. // Normals
  23385. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23386. return this;
  23387. }
  23388. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23389. temp = [];
  23390. for (index = 0; index < data.length; index += 3) {
  23391. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23392. }
  23393. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23394. // flip faces?
  23395. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23396. this.flipFaces();
  23397. }
  23398. // Restore submeshes
  23399. this.releaseSubMeshes();
  23400. this.subMeshes = submeshes;
  23401. return this;
  23402. };
  23403. /**
  23404. * Modifies the mesh geometry according to its own current World Matrix.
  23405. * The mesh World Matrix is then reset.
  23406. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23407. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23408. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23409. * Returns the Mesh.
  23410. */
  23411. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23412. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23413. this.scaling.copyFromFloats(1, 1, 1);
  23414. this.position.copyFromFloats(0, 0, 0);
  23415. this.rotation.copyFromFloats(0, 0, 0);
  23416. //only if quaternion is already set
  23417. if (this.rotationQuaternion) {
  23418. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23419. }
  23420. this._worldMatrix = BABYLON.Matrix.Identity();
  23421. return this;
  23422. };
  23423. Object.defineProperty(Mesh.prototype, "_positions", {
  23424. // Cache
  23425. get: function () {
  23426. if (this._geometry) {
  23427. return this._geometry._positions;
  23428. }
  23429. return null;
  23430. },
  23431. enumerable: true,
  23432. configurable: true
  23433. });
  23434. Mesh.prototype._resetPointsArrayCache = function () {
  23435. if (this._geometry) {
  23436. this._geometry._resetPointsArrayCache();
  23437. }
  23438. return this;
  23439. };
  23440. Mesh.prototype._generatePointsArray = function () {
  23441. if (this._geometry) {
  23442. return this._geometry._generatePointsArray();
  23443. }
  23444. return false;
  23445. };
  23446. /**
  23447. * Returns a new Mesh object generated from the current mesh properties.
  23448. * This method must not get confused with createInstance().
  23449. * The parameter `name` is a string, the name given to the new mesh.
  23450. * The optional parameter `newParent` can be any Node object (default `null`).
  23451. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23452. * 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.
  23453. */
  23454. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23455. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23456. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23457. };
  23458. /**
  23459. * Disposes the mesh.
  23460. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23461. */
  23462. Mesh.prototype.dispose = function (doNotRecurse) {
  23463. var _this = this;
  23464. this.morphTargetManager = null;
  23465. if (this._geometry) {
  23466. this._geometry.releaseForMesh(this, true);
  23467. }
  23468. // Sources
  23469. var meshes = this.getScene().meshes;
  23470. meshes.forEach(function (mesh) {
  23471. if (mesh._source && mesh._source === _this) {
  23472. mesh._source = null;
  23473. }
  23474. });
  23475. this._source = null;
  23476. // Instances
  23477. if (this._instancesBuffer) {
  23478. this._instancesBuffer.dispose();
  23479. this._instancesBuffer = null;
  23480. }
  23481. while (this.instances.length) {
  23482. this.instances[0].dispose();
  23483. }
  23484. // Highlight layers.
  23485. var highlightLayers = this.getScene().highlightLayers;
  23486. for (var i = 0; i < highlightLayers.length; i++) {
  23487. var highlightLayer = highlightLayers[i];
  23488. if (highlightLayer) {
  23489. highlightLayer.removeMesh(this);
  23490. highlightLayer.removeExcludedMesh(this);
  23491. }
  23492. }
  23493. _super.prototype.dispose.call(this, doNotRecurse);
  23494. };
  23495. /**
  23496. * Modifies the mesh geometry according to a displacement map.
  23497. * 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.
  23498. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23499. * This method returns nothing.
  23500. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23501. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23502. * 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.
  23503. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23504. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23505. *
  23506. * Returns the Mesh.
  23507. */
  23508. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23509. var _this = this;
  23510. var scene = this.getScene();
  23511. var onload = function (img) {
  23512. // Getting height map data
  23513. var canvas = document.createElement("canvas");
  23514. var context = canvas.getContext("2d");
  23515. var heightMapWidth = img.width;
  23516. var heightMapHeight = img.height;
  23517. canvas.width = heightMapWidth;
  23518. canvas.height = heightMapHeight;
  23519. context.drawImage(img, 0, 0);
  23520. // Create VertexData from map data
  23521. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23522. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23523. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23524. //execute success callback, if set
  23525. if (onSuccess) {
  23526. onSuccess(_this);
  23527. }
  23528. };
  23529. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23530. return this;
  23531. };
  23532. /**
  23533. * Modifies the mesh geometry according to a displacementMap buffer.
  23534. * 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.
  23535. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23536. * This method returns nothing.
  23537. * 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.
  23538. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23539. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23540. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23541. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23542. *
  23543. * Returns the Mesh.
  23544. */
  23545. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23546. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23547. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23548. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23549. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23550. return this;
  23551. }
  23552. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23553. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23554. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23555. var position = BABYLON.Vector3.Zero();
  23556. var normal = BABYLON.Vector3.Zero();
  23557. var uv = BABYLON.Vector2.Zero();
  23558. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23559. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23560. for (var index = 0; index < positions.length; index += 3) {
  23561. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23562. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23563. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23564. // Compute height
  23565. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23566. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23567. var pos = (u + v * heightMapWidth) * 4;
  23568. var r = buffer[pos] / 255.0;
  23569. var g = buffer[pos + 1] / 255.0;
  23570. var b = buffer[pos + 2] / 255.0;
  23571. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23572. normal.normalize();
  23573. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23574. position = position.add(normal);
  23575. position.toArray(positions, index);
  23576. }
  23577. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23578. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23579. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23580. return this;
  23581. };
  23582. /**
  23583. * Modify the mesh to get a flat shading rendering.
  23584. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23585. * This method returns the Mesh.
  23586. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23587. */
  23588. Mesh.prototype.convertToFlatShadedMesh = function () {
  23589. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23590. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23591. var kinds = this.getVerticesDataKinds();
  23592. var vbs = {};
  23593. var data = {};
  23594. var newdata = {};
  23595. var updatableNormals = false;
  23596. var kindIndex;
  23597. var kind;
  23598. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23599. kind = kinds[kindIndex];
  23600. var vertexBuffer = this.getVertexBuffer(kind);
  23601. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23602. updatableNormals = vertexBuffer.isUpdatable();
  23603. kinds.splice(kindIndex, 1);
  23604. kindIndex--;
  23605. continue;
  23606. }
  23607. vbs[kind] = vertexBuffer;
  23608. data[kind] = vbs[kind].getData();
  23609. newdata[kind] = [];
  23610. }
  23611. // Save previous submeshes
  23612. var previousSubmeshes = this.subMeshes.slice(0);
  23613. var indices = this.getIndices();
  23614. var totalIndices = this.getTotalIndices();
  23615. // Generating unique vertices per face
  23616. var index;
  23617. for (index = 0; index < totalIndices; index++) {
  23618. var vertexIndex = indices[index];
  23619. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23620. kind = kinds[kindIndex];
  23621. var stride = vbs[kind].getStrideSize();
  23622. for (var offset = 0; offset < stride; offset++) {
  23623. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23624. }
  23625. }
  23626. }
  23627. // Updating faces & normal
  23628. var normals = [];
  23629. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23630. for (index = 0; index < totalIndices; index += 3) {
  23631. indices[index] = index;
  23632. indices[index + 1] = index + 1;
  23633. indices[index + 2] = index + 2;
  23634. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23635. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23636. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23637. var p1p2 = p1.subtract(p2);
  23638. var p3p2 = p3.subtract(p2);
  23639. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23640. // Store same normals for every vertex
  23641. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23642. normals.push(normal.x);
  23643. normals.push(normal.y);
  23644. normals.push(normal.z);
  23645. }
  23646. }
  23647. this.setIndices(indices);
  23648. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23649. // Updating vertex buffers
  23650. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23651. kind = kinds[kindIndex];
  23652. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23653. }
  23654. // Updating submeshes
  23655. this.releaseSubMeshes();
  23656. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23657. var previousOne = previousSubmeshes[submeshIndex];
  23658. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23659. }
  23660. this.synchronizeInstances();
  23661. return this;
  23662. };
  23663. /**
  23664. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23665. * In other words, more vertices, no more indices and a single bigger VBO.
  23666. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23667. * Returns the Mesh.
  23668. */
  23669. Mesh.prototype.convertToUnIndexedMesh = function () {
  23670. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23671. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23672. var kinds = this.getVerticesDataKinds();
  23673. var vbs = {};
  23674. var data = {};
  23675. var newdata = {};
  23676. var kindIndex;
  23677. var kind;
  23678. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23679. kind = kinds[kindIndex];
  23680. var vertexBuffer = this.getVertexBuffer(kind);
  23681. vbs[kind] = vertexBuffer;
  23682. data[kind] = vbs[kind].getData();
  23683. newdata[kind] = [];
  23684. }
  23685. // Save previous submeshes
  23686. var previousSubmeshes = this.subMeshes.slice(0);
  23687. var indices = this.getIndices();
  23688. var totalIndices = this.getTotalIndices();
  23689. // Generating unique vertices per face
  23690. var index;
  23691. for (index = 0; index < totalIndices; index++) {
  23692. var vertexIndex = indices[index];
  23693. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23694. kind = kinds[kindIndex];
  23695. var stride = vbs[kind].getStrideSize();
  23696. for (var offset = 0; offset < stride; offset++) {
  23697. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23698. }
  23699. }
  23700. }
  23701. // Updating indices
  23702. for (index = 0; index < totalIndices; index += 3) {
  23703. indices[index] = index;
  23704. indices[index + 1] = index + 1;
  23705. indices[index + 2] = index + 2;
  23706. }
  23707. this.setIndices(indices);
  23708. // Updating vertex buffers
  23709. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23710. kind = kinds[kindIndex];
  23711. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23712. }
  23713. // Updating submeshes
  23714. this.releaseSubMeshes();
  23715. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23716. var previousOne = previousSubmeshes[submeshIndex];
  23717. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23718. }
  23719. this._unIndexed = true;
  23720. this.synchronizeInstances();
  23721. return this;
  23722. };
  23723. /**
  23724. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23725. * This method returns the Mesh.
  23726. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23727. */
  23728. Mesh.prototype.flipFaces = function (flipNormals) {
  23729. if (flipNormals === void 0) { flipNormals = false; }
  23730. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23731. var i;
  23732. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  23733. for (i = 0; i < vertex_data.normals.length; i++) {
  23734. vertex_data.normals[i] *= -1;
  23735. }
  23736. }
  23737. if (vertex_data.indices) {
  23738. var temp;
  23739. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23740. // reassign indices
  23741. temp = vertex_data.indices[i + 1];
  23742. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23743. vertex_data.indices[i + 2] = temp;
  23744. }
  23745. }
  23746. vertex_data.applyToMesh(this);
  23747. return this;
  23748. };
  23749. // Instances
  23750. /**
  23751. * Creates a new InstancedMesh object from the mesh model.
  23752. * An instance shares the same properties and the same material than its model.
  23753. * Only these properties of each instance can then be set individually :
  23754. * - position
  23755. * - rotation
  23756. * - rotationQuaternion
  23757. * - setPivotMatrix
  23758. * - scaling
  23759. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23760. * Warning : this method is not supported for Line mesh and LineSystem
  23761. */
  23762. Mesh.prototype.createInstance = function (name) {
  23763. return new BABYLON.InstancedMesh(name, this);
  23764. };
  23765. /**
  23766. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23767. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23768. * This method returns the Mesh.
  23769. */
  23770. Mesh.prototype.synchronizeInstances = function () {
  23771. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23772. var instance = this.instances[instanceIndex];
  23773. instance._syncSubMeshes();
  23774. }
  23775. return this;
  23776. };
  23777. /**
  23778. * Simplify the mesh according to the given array of settings.
  23779. * Function will return immediately and will simplify async. It returns the Mesh.
  23780. * @param settings a collection of simplification settings.
  23781. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23782. * @param type the type of simplification to run.
  23783. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23784. */
  23785. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23786. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23787. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23788. this.getScene().simplificationQueue.addTask({
  23789. settings: settings,
  23790. parallelProcessing: parallelProcessing,
  23791. mesh: this,
  23792. simplificationType: simplificationType,
  23793. successCallback: successCallback
  23794. });
  23795. return this;
  23796. };
  23797. /**
  23798. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23799. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23800. * This should be used together with the simplification to avoid disappearing triangles.
  23801. * Returns the Mesh.
  23802. * @param successCallback an optional success callback to be called after the optimization finished.
  23803. */
  23804. Mesh.prototype.optimizeIndices = function (successCallback) {
  23805. var _this = this;
  23806. var indices = this.getIndices();
  23807. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23808. if (!positions || !indices) {
  23809. return this;
  23810. }
  23811. var vectorPositions = new Array();
  23812. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23813. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23814. }
  23815. var dupes = new Array();
  23816. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23817. var realPos = vectorPositions.length - 1 - iteration;
  23818. var testedPosition = vectorPositions[realPos];
  23819. for (var j = 0; j < realPos; ++j) {
  23820. var againstPosition = vectorPositions[j];
  23821. if (testedPosition.equals(againstPosition)) {
  23822. dupes[realPos] = j;
  23823. break;
  23824. }
  23825. }
  23826. }, function () {
  23827. for (var i = 0; i < indices.length; ++i) {
  23828. indices[i] = dupes[indices[i]] || indices[i];
  23829. }
  23830. //indices are now reordered
  23831. var originalSubMeshes = _this.subMeshes.slice(0);
  23832. _this.setIndices(indices);
  23833. _this.subMeshes = originalSubMeshes;
  23834. if (successCallback) {
  23835. successCallback(_this);
  23836. }
  23837. });
  23838. return this;
  23839. };
  23840. Mesh.prototype.serialize = function (serializationObject) {
  23841. serializationObject.name = this.name;
  23842. serializationObject.id = this.id;
  23843. serializationObject.type = this.getClassName();
  23844. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  23845. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23846. }
  23847. serializationObject.position = this.position.asArray();
  23848. if (this.rotationQuaternion) {
  23849. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  23850. }
  23851. else if (this.rotation) {
  23852. serializationObject.rotation = this.rotation.asArray();
  23853. }
  23854. serializationObject.scaling = this.scaling.asArray();
  23855. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  23856. serializationObject.isEnabled = this.isEnabled();
  23857. serializationObject.isVisible = this.isVisible;
  23858. serializationObject.infiniteDistance = this.infiniteDistance;
  23859. serializationObject.pickable = this.isPickable;
  23860. serializationObject.receiveShadows = this.receiveShadows;
  23861. serializationObject.billboardMode = this.billboardMode;
  23862. serializationObject.visibility = this.visibility;
  23863. serializationObject.checkCollisions = this.checkCollisions;
  23864. serializationObject.isBlocker = this.isBlocker;
  23865. // Parent
  23866. if (this.parent) {
  23867. serializationObject.parentId = this.parent.id;
  23868. }
  23869. // Geometry
  23870. var geometry = this._geometry;
  23871. if (geometry) {
  23872. var geometryId = geometry.id;
  23873. serializationObject.geometryId = geometryId;
  23874. // SubMeshes
  23875. serializationObject.subMeshes = [];
  23876. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  23877. var subMesh = this.subMeshes[subIndex];
  23878. serializationObject.subMeshes.push({
  23879. materialIndex: subMesh.materialIndex,
  23880. verticesStart: subMesh.verticesStart,
  23881. verticesCount: subMesh.verticesCount,
  23882. indexStart: subMesh.indexStart,
  23883. indexCount: subMesh.indexCount
  23884. });
  23885. }
  23886. }
  23887. // Material
  23888. if (this.material) {
  23889. serializationObject.materialId = this.material.id;
  23890. }
  23891. else {
  23892. this.material = null;
  23893. }
  23894. // Morph targets
  23895. if (this.morphTargetManager) {
  23896. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  23897. }
  23898. // Skeleton
  23899. if (this.skeleton) {
  23900. serializationObject.skeletonId = this.skeleton.id;
  23901. }
  23902. // Physics
  23903. //TODO implement correct serialization for physics impostors.
  23904. var impostor = this.getPhysicsImpostor();
  23905. if (impostor) {
  23906. serializationObject.physicsMass = impostor.getParam("mass");
  23907. serializationObject.physicsFriction = impostor.getParam("friction");
  23908. serializationObject.physicsRestitution = impostor.getParam("mass");
  23909. serializationObject.physicsImpostor = impostor.type;
  23910. }
  23911. // Metadata
  23912. if (this.metadata) {
  23913. serializationObject.metadata = this.metadata;
  23914. }
  23915. // Instances
  23916. serializationObject.instances = [];
  23917. for (var index = 0; index < this.instances.length; index++) {
  23918. var instance = this.instances[index];
  23919. var serializationInstance = {
  23920. name: instance.name,
  23921. position: instance.position.asArray(),
  23922. scaling: instance.scaling.asArray()
  23923. };
  23924. if (instance.rotationQuaternion) {
  23925. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23926. }
  23927. else if (instance.rotation) {
  23928. serializationInstance.rotation = instance.rotation.asArray();
  23929. }
  23930. serializationObject.instances.push(serializationInstance);
  23931. // Animations
  23932. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23933. serializationInstance.ranges = instance.serializeAnimationRanges();
  23934. }
  23935. //
  23936. // Animations
  23937. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23938. serializationObject.ranges = this.serializeAnimationRanges();
  23939. // Layer mask
  23940. serializationObject.layerMask = this.layerMask;
  23941. // Alpha
  23942. serializationObject.alphaIndex = this.alphaIndex;
  23943. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23944. // Overlay
  23945. serializationObject.overlayAlpha = this.overlayAlpha;
  23946. serializationObject.overlayColor = this.overlayColor.asArray();
  23947. serializationObject.renderOverlay = this.renderOverlay;
  23948. // Fog
  23949. serializationObject.applyFog = this.applyFog;
  23950. // Action Manager
  23951. if (this.actionManager) {
  23952. serializationObject.actions = this.actionManager.serialize(this.name);
  23953. }
  23954. };
  23955. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23956. if (!this.geometry) {
  23957. return;
  23958. }
  23959. this._markSubMeshesAsAttributesDirty();
  23960. var morphTargetManager = this._morphTargetManager;
  23961. if (morphTargetManager && morphTargetManager.vertexCount) {
  23962. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23963. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23964. this.morphTargetManager = null;
  23965. return;
  23966. }
  23967. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  23968. var morphTarget = morphTargetManager.getActiveTarget(index);
  23969. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23970. if (morphTarget.hasNormals) {
  23971. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23972. }
  23973. if (morphTarget.hasTangents) {
  23974. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23975. }
  23976. }
  23977. }
  23978. else {
  23979. var index = 0;
  23980. // Positions
  23981. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23982. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23983. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23984. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23985. }
  23986. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23987. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23988. }
  23989. index++;
  23990. }
  23991. }
  23992. };
  23993. // Statics
  23994. /**
  23995. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23996. * The parameter `parsedMesh` is the mesh to be copied.
  23997. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23998. */
  23999. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24000. var mesh;
  24001. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24002. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24003. }
  24004. else {
  24005. mesh = new Mesh(parsedMesh.name, scene);
  24006. }
  24007. mesh.id = parsedMesh.id;
  24008. if (BABYLON.Tags) {
  24009. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24010. }
  24011. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24012. if (parsedMesh.metadata !== undefined) {
  24013. mesh.metadata = parsedMesh.metadata;
  24014. }
  24015. if (parsedMesh.rotationQuaternion) {
  24016. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24017. }
  24018. else if (parsedMesh.rotation) {
  24019. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24020. }
  24021. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24022. if (parsedMesh.localMatrix) {
  24023. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24024. }
  24025. else if (parsedMesh.pivotMatrix) {
  24026. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24027. }
  24028. mesh.setEnabled(parsedMesh.isEnabled);
  24029. mesh.isVisible = parsedMesh.isVisible;
  24030. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24031. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24032. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24033. if (parsedMesh.applyFog !== undefined) {
  24034. mesh.applyFog = parsedMesh.applyFog;
  24035. }
  24036. if (parsedMesh.pickable !== undefined) {
  24037. mesh.isPickable = parsedMesh.pickable;
  24038. }
  24039. if (parsedMesh.alphaIndex !== undefined) {
  24040. mesh.alphaIndex = parsedMesh.alphaIndex;
  24041. }
  24042. mesh.receiveShadows = parsedMesh.receiveShadows;
  24043. mesh.billboardMode = parsedMesh.billboardMode;
  24044. if (parsedMesh.visibility !== undefined) {
  24045. mesh.visibility = parsedMesh.visibility;
  24046. }
  24047. mesh.checkCollisions = parsedMesh.checkCollisions;
  24048. if (parsedMesh.isBlocker !== undefined) {
  24049. mesh.isBlocker = parsedMesh.isBlocker;
  24050. }
  24051. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24052. // freezeWorldMatrix
  24053. if (parsedMesh.freezeWorldMatrix) {
  24054. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24055. }
  24056. // Parent
  24057. if (parsedMesh.parentId) {
  24058. mesh._waitingParentId = parsedMesh.parentId;
  24059. }
  24060. // Actions
  24061. if (parsedMesh.actions !== undefined) {
  24062. mesh._waitingActions = parsedMesh.actions;
  24063. }
  24064. // Overlay
  24065. if (parsedMesh.overlayAlpha !== undefined) {
  24066. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24067. }
  24068. if (parsedMesh.overlayColor !== undefined) {
  24069. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24070. }
  24071. if (parsedMesh.renderOverlay !== undefined) {
  24072. mesh.renderOverlay = parsedMesh.renderOverlay;
  24073. }
  24074. // Geometry
  24075. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24076. if (parsedMesh.delayLoadingFile) {
  24077. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24078. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24079. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24080. if (parsedMesh._binaryInfo) {
  24081. mesh._binaryInfo = parsedMesh._binaryInfo;
  24082. }
  24083. mesh._delayInfo = [];
  24084. if (parsedMesh.hasUVs) {
  24085. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24086. }
  24087. if (parsedMesh.hasUVs2) {
  24088. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24089. }
  24090. if (parsedMesh.hasUVs3) {
  24091. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24092. }
  24093. if (parsedMesh.hasUVs4) {
  24094. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24095. }
  24096. if (parsedMesh.hasUVs5) {
  24097. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24098. }
  24099. if (parsedMesh.hasUVs6) {
  24100. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24101. }
  24102. if (parsedMesh.hasColors) {
  24103. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24104. }
  24105. if (parsedMesh.hasMatricesIndices) {
  24106. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24107. }
  24108. if (parsedMesh.hasMatricesWeights) {
  24109. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24110. }
  24111. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24112. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24113. mesh._checkDelayState();
  24114. }
  24115. }
  24116. else {
  24117. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24118. }
  24119. // Material
  24120. if (parsedMesh.materialId) {
  24121. mesh.setMaterialByID(parsedMesh.materialId);
  24122. }
  24123. else {
  24124. mesh.material = null;
  24125. }
  24126. // Morph targets
  24127. if (parsedMesh.morphTargetManagerId > -1) {
  24128. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24129. }
  24130. // Skeleton
  24131. if (parsedMesh.skeletonId > -1) {
  24132. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24133. if (parsedMesh.numBoneInfluencers) {
  24134. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24135. }
  24136. }
  24137. // Animations
  24138. if (parsedMesh.animations) {
  24139. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24140. var parsedAnimation = parsedMesh.animations[animationIndex];
  24141. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24142. }
  24143. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24144. }
  24145. if (parsedMesh.autoAnimate) {
  24146. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24147. }
  24148. // Layer Mask
  24149. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24150. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24151. }
  24152. else {
  24153. mesh.layerMask = 0x0FFFFFFF;
  24154. }
  24155. // Physics
  24156. if (parsedMesh.physicsImpostor) {
  24157. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24158. mass: parsedMesh.physicsMass,
  24159. friction: parsedMesh.physicsFriction,
  24160. restitution: parsedMesh.physicsRestitution
  24161. }, scene);
  24162. }
  24163. // Instances
  24164. if (parsedMesh.instances) {
  24165. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24166. var parsedInstance = parsedMesh.instances[index];
  24167. var instance = mesh.createInstance(parsedInstance.name);
  24168. if (BABYLON.Tags) {
  24169. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24170. }
  24171. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24172. if (parsedInstance.parentId) {
  24173. instance._waitingParentId = parsedInstance.parentId;
  24174. }
  24175. if (parsedInstance.rotationQuaternion) {
  24176. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24177. }
  24178. else if (parsedInstance.rotation) {
  24179. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24180. }
  24181. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24182. instance.checkCollisions = mesh.checkCollisions;
  24183. if (parsedMesh.animations) {
  24184. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24185. parsedAnimation = parsedMesh.animations[animationIndex];
  24186. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24187. }
  24188. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24189. }
  24190. }
  24191. }
  24192. return mesh;
  24193. };
  24194. /**
  24195. * Creates a ribbon mesh.
  24196. * Please consider using the same method from the MeshBuilder class instead.
  24197. * 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.
  24198. *
  24199. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24200. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24201. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24202. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24203. * 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.
  24204. * 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.
  24205. * 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
  24206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24207. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24209. */
  24210. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24211. if (closeArray === void 0) { closeArray = false; }
  24212. if (updatable === void 0) { updatable = false; }
  24213. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24214. pathArray: pathArray,
  24215. closeArray: closeArray,
  24216. closePath: closePath,
  24217. offset: offset,
  24218. updatable: updatable,
  24219. sideOrientation: sideOrientation,
  24220. instance: instance
  24221. }, scene);
  24222. };
  24223. /**
  24224. * Creates a plane polygonal mesh. By default, this is a disc.
  24225. * Please consider using the same method from the MeshBuilder class instead.
  24226. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24227. * 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.
  24228. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24229. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24231. */
  24232. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24233. if (scene === void 0) { scene = null; }
  24234. var options = {
  24235. radius: radius,
  24236. tessellation: tessellation,
  24237. sideOrientation: sideOrientation,
  24238. updatable: updatable
  24239. };
  24240. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24241. };
  24242. /**
  24243. * Creates a box mesh.
  24244. * Please consider using the same method from the MeshBuilder class instead.
  24245. * The parameter `size` sets the size (float) of each box side (default 1).
  24246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24247. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24249. */
  24250. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24251. if (scene === void 0) { scene = null; }
  24252. var options = {
  24253. size: size,
  24254. sideOrientation: sideOrientation,
  24255. updatable: updatable
  24256. };
  24257. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24258. };
  24259. /**
  24260. * Creates a sphere mesh.
  24261. * Please consider using the same method from the MeshBuilder class instead.
  24262. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24263. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24265. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24267. */
  24268. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24269. var options = {
  24270. segments: segments,
  24271. diameterX: diameter,
  24272. diameterY: diameter,
  24273. diameterZ: diameter,
  24274. sideOrientation: sideOrientation,
  24275. updatable: updatable
  24276. };
  24277. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24278. };
  24279. /**
  24280. * Creates a cylinder or a cone mesh.
  24281. * Please consider using the same method from the MeshBuilder class instead.
  24282. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24283. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24284. * 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.
  24285. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24286. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24287. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24288. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24290. */
  24291. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24292. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24293. if (scene !== undefined) {
  24294. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24295. updatable = scene;
  24296. }
  24297. scene = subdivisions;
  24298. subdivisions = 1;
  24299. }
  24300. var options = {
  24301. height: height,
  24302. diameterTop: diameterTop,
  24303. diameterBottom: diameterBottom,
  24304. tessellation: tessellation,
  24305. subdivisions: subdivisions,
  24306. sideOrientation: sideOrientation,
  24307. updatable: updatable
  24308. };
  24309. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24310. };
  24311. // Torus (Code from SharpDX.org)
  24312. /**
  24313. * Creates a torus mesh.
  24314. * Please consider using the same method from the MeshBuilder class instead.
  24315. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24316. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24317. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24319. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24321. */
  24322. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24323. var options = {
  24324. diameter: diameter,
  24325. thickness: thickness,
  24326. tessellation: tessellation,
  24327. sideOrientation: sideOrientation,
  24328. updatable: updatable
  24329. };
  24330. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24331. };
  24332. /**
  24333. * Creates a torus knot mesh.
  24334. * Please consider using the same method from the MeshBuilder class instead.
  24335. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24336. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24337. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24338. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24339. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24340. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24342. */
  24343. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24344. var options = {
  24345. radius: radius,
  24346. tube: tube,
  24347. radialSegments: radialSegments,
  24348. tubularSegments: tubularSegments,
  24349. p: p,
  24350. q: q,
  24351. sideOrientation: sideOrientation,
  24352. updatable: updatable
  24353. };
  24354. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24355. };
  24356. /**
  24357. * Creates a line mesh.
  24358. * Please consider using the same method from the MeshBuilder class instead.
  24359. * 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.
  24360. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24361. * The parameter `points` is an array successive Vector3.
  24362. * 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
  24363. * When updating an instance, remember that only point positions can change, not the number of points.
  24364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24365. */
  24366. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24367. if (scene === void 0) { scene = null; }
  24368. if (updatable === void 0) { updatable = false; }
  24369. if (instance === void 0) { instance = null; }
  24370. var options = {
  24371. points: points,
  24372. updatable: updatable,
  24373. instance: instance
  24374. };
  24375. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24376. };
  24377. /**
  24378. * Creates a dashed line mesh.
  24379. * Please consider using the same method from the MeshBuilder class instead.
  24380. * 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.
  24381. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24382. * The parameter `points` is an array successive Vector3.
  24383. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24384. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24385. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24386. * 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
  24387. * When updating an instance, remember that only point positions can change, not the number of points.
  24388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24389. */
  24390. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24391. if (scene === void 0) { scene = null; }
  24392. var options = {
  24393. points: points,
  24394. dashSize: dashSize,
  24395. gapSize: gapSize,
  24396. dashNb: dashNb,
  24397. updatable: updatable,
  24398. instance: instance
  24399. };
  24400. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24401. };
  24402. /**
  24403. * Creates a polygon mesh.
  24404. * Please consider using the same method from the MeshBuilder class instead.
  24405. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24406. * 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.
  24407. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24409. * Remember you can only change the shape positions, not their number when updating a polygon.
  24410. */
  24411. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24412. var options = {
  24413. shape: shape,
  24414. holes: holes,
  24415. updatable: updatable,
  24416. sideOrientation: sideOrientation
  24417. };
  24418. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24419. };
  24420. /**
  24421. * Creates an extruded polygon mesh, with depth in the Y direction.
  24422. * Please consider using the same method from the MeshBuilder class instead.
  24423. */
  24424. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24425. var options = {
  24426. shape: shape,
  24427. holes: holes,
  24428. depth: depth,
  24429. updatable: updatable,
  24430. sideOrientation: sideOrientation
  24431. };
  24432. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24433. };
  24434. /**
  24435. * Creates an extruded shape mesh.
  24436. * 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.
  24437. * Please consider using the same method from the MeshBuilder class instead.
  24438. *
  24439. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24440. * 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
  24441. * extruded along the Z axis.
  24442. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24443. * 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.
  24444. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24445. * 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
  24446. * 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
  24447. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24448. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24451. */
  24452. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24453. if (scene === void 0) { scene = null; }
  24454. var options = {
  24455. shape: shape,
  24456. path: path,
  24457. scale: scale,
  24458. rotation: rotation,
  24459. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24460. sideOrientation: sideOrientation,
  24461. instance: instance,
  24462. updatable: updatable
  24463. };
  24464. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24465. };
  24466. /**
  24467. * Creates an custom extruded shape mesh.
  24468. * 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.
  24469. * Please consider using the same method from the MeshBuilder class instead.
  24470. *
  24471. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24472. * 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
  24473. * extruded along the Z axis.
  24474. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24475. * 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
  24476. * and the distance of this point from the begining of the path :
  24477. * ```javascript
  24478. * var rotationFunction = function(i, distance) {
  24479. * // do things
  24480. * return rotationValue; }
  24481. * ```
  24482. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24483. * 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
  24484. * and the distance of this point from the begining of the path :
  24485. * ```javascript
  24486. * var scaleFunction = function(i, distance) {
  24487. * // do things
  24488. * return scaleValue;}
  24489. * ```
  24490. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24491. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24492. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24493. * 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
  24494. * 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
  24495. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24496. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24497. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24498. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24499. */
  24500. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24501. var options = {
  24502. shape: shape,
  24503. path: path,
  24504. scaleFunction: scaleFunction,
  24505. rotationFunction: rotationFunction,
  24506. ribbonCloseArray: ribbonCloseArray,
  24507. ribbonClosePath: ribbonClosePath,
  24508. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24509. sideOrientation: sideOrientation,
  24510. instance: instance,
  24511. updatable: updatable
  24512. };
  24513. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24514. };
  24515. /**
  24516. * Creates lathe mesh.
  24517. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24518. * Please consider using the same method from the MeshBuilder class instead.
  24519. * 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
  24520. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24521. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24522. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24523. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24524. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24526. */
  24527. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24528. var options = {
  24529. shape: shape,
  24530. radius: radius,
  24531. tessellation: tessellation,
  24532. sideOrientation: sideOrientation,
  24533. updatable: updatable
  24534. };
  24535. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24536. };
  24537. /**
  24538. * Creates a plane mesh.
  24539. * Please consider using the same method from the MeshBuilder class instead.
  24540. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24542. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24544. */
  24545. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24546. var options = {
  24547. size: size,
  24548. width: size,
  24549. height: size,
  24550. sideOrientation: sideOrientation,
  24551. updatable: updatable
  24552. };
  24553. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24554. };
  24555. /**
  24556. * Creates a ground mesh.
  24557. * Please consider using the same method from the MeshBuilder class instead.
  24558. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24559. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24560. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24561. */
  24562. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24563. var options = {
  24564. width: width,
  24565. height: height,
  24566. subdivisions: subdivisions,
  24567. updatable: updatable
  24568. };
  24569. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24570. };
  24571. /**
  24572. * Creates a tiled ground mesh.
  24573. * Please consider using the same method from the MeshBuilder class instead.
  24574. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24575. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24576. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24577. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24578. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24579. * numbers of subdivisions on the ground width and height of each tile.
  24580. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24581. */
  24582. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24583. var options = {
  24584. xmin: xmin,
  24585. zmin: zmin,
  24586. xmax: xmax,
  24587. zmax: zmax,
  24588. subdivisions: subdivisions,
  24589. precision: precision,
  24590. updatable: updatable
  24591. };
  24592. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24593. };
  24594. /**
  24595. * Creates a ground mesh from a height map.
  24596. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24597. * Please consider using the same method from the MeshBuilder class instead.
  24598. * The parameter `url` sets the URL of the height map image resource.
  24599. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24600. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24601. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24602. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24603. * 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).
  24604. * This function is passed the newly built mesh :
  24605. * ```javascript
  24606. * function(mesh) { // do things
  24607. * return; }
  24608. * ```
  24609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24610. */
  24611. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24612. var options = {
  24613. width: width,
  24614. height: height,
  24615. subdivisions: subdivisions,
  24616. minHeight: minHeight,
  24617. maxHeight: maxHeight,
  24618. updatable: updatable,
  24619. onReady: onReady
  24620. };
  24621. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24622. };
  24623. /**
  24624. * Creates a tube mesh.
  24625. * 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.
  24626. * Please consider using the same method from the MeshBuilder class instead.
  24627. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24628. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24629. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24630. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24631. * 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.
  24632. * It must return a radius value (positive float) :
  24633. * ```javascript
  24634. * var radiusFunction = function(i, distance) {
  24635. * // do things
  24636. * return radius; }
  24637. * ```
  24638. * 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
  24639. * 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
  24640. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24641. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24643. */
  24644. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24645. var options = {
  24646. path: path,
  24647. radius: radius,
  24648. tessellation: tessellation,
  24649. radiusFunction: radiusFunction,
  24650. arc: 1,
  24651. cap: cap,
  24652. updatable: updatable,
  24653. sideOrientation: sideOrientation,
  24654. instance: instance
  24655. };
  24656. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24657. };
  24658. /**
  24659. * Creates a polyhedron mesh.
  24660. * Please consider using the same method from the MeshBuilder class instead.
  24661. * 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
  24662. * to choose the wanted type.
  24663. * The parameter `size` (positive float, default 1) sets the polygon size.
  24664. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24665. * 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`.
  24666. * 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
  24667. * 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)`).
  24668. * 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
  24669. * 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.
  24670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24671. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24672. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24673. */
  24674. Mesh.CreatePolyhedron = function (name, options, scene) {
  24675. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24676. };
  24677. /**
  24678. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24679. * Please consider using the same method from the MeshBuilder class instead.
  24680. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24681. * 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`).
  24682. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24683. * 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.
  24684. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24685. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24687. */
  24688. Mesh.CreateIcoSphere = function (name, options, scene) {
  24689. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24690. };
  24691. /**
  24692. * Creates a decal mesh.
  24693. * Please consider using the same method from the MeshBuilder class instead.
  24694. * 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.
  24695. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24696. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24697. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24698. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24699. */
  24700. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24701. var options = {
  24702. position: position,
  24703. normal: normal,
  24704. size: size,
  24705. angle: angle
  24706. };
  24707. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24708. };
  24709. // Skeletons
  24710. /**
  24711. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24712. */
  24713. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24714. if (!this._sourcePositions) {
  24715. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24716. if (!source) {
  24717. return this._sourcePositions;
  24718. }
  24719. this._sourcePositions = new Float32Array(source);
  24720. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  24721. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24722. }
  24723. }
  24724. return this._sourcePositions;
  24725. };
  24726. /**
  24727. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24728. */
  24729. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24730. if (!this._sourceNormals) {
  24731. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24732. if (!source) {
  24733. return this._sourceNormals;
  24734. }
  24735. this._sourceNormals = new Float32Array(source);
  24736. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  24737. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24738. }
  24739. }
  24740. return this._sourceNormals;
  24741. };
  24742. /**
  24743. * Updates the vertex buffer by applying transformation from the bones.
  24744. * Returns the Mesh.
  24745. *
  24746. * @param {skeleton} skeleton to apply
  24747. */
  24748. Mesh.prototype.applySkeleton = function (skeleton) {
  24749. if (!this.geometry) {
  24750. return this;
  24751. }
  24752. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24753. return this;
  24754. }
  24755. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24756. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24757. return this;
  24758. }
  24759. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24760. return this;
  24761. }
  24762. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24763. return this;
  24764. }
  24765. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24766. return this;
  24767. }
  24768. if (!this._sourcePositions) {
  24769. var submeshes = this.subMeshes.slice();
  24770. this.setPositionsForCPUSkinning();
  24771. this.subMeshes = submeshes;
  24772. }
  24773. if (!this._sourceNormals) {
  24774. this.setNormalsForCPUSkinning();
  24775. }
  24776. // positionsData checks for not being Float32Array will only pass at most once
  24777. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24778. if (!positionsData) {
  24779. return this;
  24780. }
  24781. if (!(positionsData instanceof Float32Array)) {
  24782. positionsData = new Float32Array(positionsData);
  24783. }
  24784. // normalsData checks for not being Float32Array will only pass at most once
  24785. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24786. if (!normalsData) {
  24787. return this;
  24788. }
  24789. if (!(normalsData instanceof Float32Array)) {
  24790. normalsData = new Float32Array(normalsData);
  24791. }
  24792. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24793. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24794. if (!matricesWeightsData || !matricesIndicesData) {
  24795. return this;
  24796. }
  24797. var needExtras = this.numBoneInfluencers > 4;
  24798. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24799. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24800. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  24801. return this;
  24802. }
  24803. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24804. var tempVector3 = BABYLON.Vector3.Zero();
  24805. var finalMatrix = new BABYLON.Matrix();
  24806. var tempMatrix = new BABYLON.Matrix();
  24807. var matWeightIdx = 0;
  24808. var inf;
  24809. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24810. var weight;
  24811. for (inf = 0; inf < 4; inf++) {
  24812. weight = matricesWeightsData[matWeightIdx + inf];
  24813. if (weight > 0) {
  24814. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24815. finalMatrix.addToSelf(tempMatrix);
  24816. }
  24817. else
  24818. break;
  24819. }
  24820. if (needExtras) {
  24821. for (inf = 0; inf < 4; inf++) {
  24822. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24823. if (weight > 0) {
  24824. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24825. finalMatrix.addToSelf(tempMatrix);
  24826. }
  24827. else
  24828. break;
  24829. }
  24830. }
  24831. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24832. tempVector3.toArray(positionsData, index);
  24833. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24834. tempVector3.toArray(normalsData, index);
  24835. finalMatrix.reset();
  24836. }
  24837. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24838. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24839. return this;
  24840. };
  24841. // Tools
  24842. /**
  24843. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24844. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24845. */
  24846. Mesh.MinMax = function (meshes) {
  24847. var minVector = null;
  24848. var maxVector = null;
  24849. meshes.forEach(function (mesh, index, array) {
  24850. var boundingInfo = mesh.getBoundingInfo();
  24851. if (!boundingInfo) {
  24852. return;
  24853. }
  24854. var boundingBox = boundingInfo.boundingBox;
  24855. if (!minVector || !maxVector) {
  24856. minVector = boundingBox.minimumWorld;
  24857. maxVector = boundingBox.maximumWorld;
  24858. }
  24859. else {
  24860. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24861. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24862. }
  24863. });
  24864. if (!minVector || !maxVector) {
  24865. return {
  24866. min: BABYLON.Vector3.Zero(),
  24867. max: BABYLON.Vector3.Zero()
  24868. };
  24869. }
  24870. return {
  24871. min: minVector,
  24872. max: maxVector
  24873. };
  24874. };
  24875. /**
  24876. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24877. */
  24878. Mesh.Center = function (meshesOrMinMaxVector) {
  24879. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24880. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24881. };
  24882. /**
  24883. * Merge the array of meshes into a single mesh for performance reasons.
  24884. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24885. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24886. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24887. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24888. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24889. */
  24890. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24891. if (disposeSource === void 0) { disposeSource = true; }
  24892. var index;
  24893. if (!allow32BitsIndices) {
  24894. var totalVertices = 0;
  24895. // Counting vertices
  24896. for (index = 0; index < meshes.length; index++) {
  24897. if (meshes[index]) {
  24898. totalVertices += meshes[index].getTotalVertices();
  24899. if (totalVertices > 65536) {
  24900. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24901. return null;
  24902. }
  24903. }
  24904. }
  24905. }
  24906. // Merge
  24907. var vertexData = null;
  24908. var otherVertexData;
  24909. var indiceArray = new Array();
  24910. var source = null;
  24911. for (index = 0; index < meshes.length; index++) {
  24912. if (meshes[index]) {
  24913. meshes[index].computeWorldMatrix(true);
  24914. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24915. otherVertexData.transform(meshes[index].getWorldMatrix());
  24916. if (vertexData) {
  24917. vertexData.merge(otherVertexData);
  24918. }
  24919. else {
  24920. vertexData = otherVertexData;
  24921. source = meshes[index];
  24922. }
  24923. if (subdivideWithSubMeshes) {
  24924. indiceArray.push(meshes[index].getTotalIndices());
  24925. }
  24926. }
  24927. }
  24928. source = source;
  24929. if (!meshSubclass) {
  24930. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24931. }
  24932. vertexData.applyToMesh(meshSubclass);
  24933. // Setting properties
  24934. meshSubclass.material = source.material;
  24935. meshSubclass.checkCollisions = source.checkCollisions;
  24936. // Cleaning
  24937. if (disposeSource) {
  24938. for (index = 0; index < meshes.length; index++) {
  24939. if (meshes[index]) {
  24940. meshes[index].dispose();
  24941. }
  24942. }
  24943. }
  24944. // Subdivide
  24945. if (subdivideWithSubMeshes) {
  24946. //-- Suppresions du submesh global
  24947. meshSubclass.releaseSubMeshes();
  24948. index = 0;
  24949. var offset = 0;
  24950. //-- aplique la subdivision en fonction du tableau d'indices
  24951. while (index < indiceArray.length) {
  24952. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24953. offset += indiceArray[index];
  24954. index++;
  24955. }
  24956. }
  24957. return meshSubclass;
  24958. };
  24959. // Consts
  24960. Mesh._FRONTSIDE = 0;
  24961. Mesh._BACKSIDE = 1;
  24962. Mesh._DOUBLESIDE = 2;
  24963. Mesh._DEFAULTSIDE = 0;
  24964. Mesh._NO_CAP = 0;
  24965. Mesh._CAP_START = 1;
  24966. Mesh._CAP_END = 2;
  24967. Mesh._CAP_ALL = 3;
  24968. return Mesh;
  24969. }(BABYLON.AbstractMesh));
  24970. BABYLON.Mesh = Mesh;
  24971. })(BABYLON || (BABYLON = {}));
  24972. //# sourceMappingURL=babylon.mesh.js.map
  24973. var BABYLON;
  24974. (function (BABYLON) {
  24975. var BaseSubMesh = /** @class */ (function () {
  24976. function BaseSubMesh() {
  24977. }
  24978. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24979. get: function () {
  24980. return this._materialEffect;
  24981. },
  24982. enumerable: true,
  24983. configurable: true
  24984. });
  24985. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24986. if (defines === void 0) { defines = null; }
  24987. if (this._materialEffect === effect) {
  24988. if (!effect) {
  24989. this._materialDefines = null;
  24990. }
  24991. return;
  24992. }
  24993. this._materialDefines = defines;
  24994. this._materialEffect = effect;
  24995. };
  24996. return BaseSubMesh;
  24997. }());
  24998. BABYLON.BaseSubMesh = BaseSubMesh;
  24999. var SubMesh = /** @class */ (function (_super) {
  25000. __extends(SubMesh, _super);
  25001. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25002. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25003. var _this = _super.call(this) || this;
  25004. _this.materialIndex = materialIndex;
  25005. _this.verticesStart = verticesStart;
  25006. _this.verticesCount = verticesCount;
  25007. _this.indexStart = indexStart;
  25008. _this.indexCount = indexCount;
  25009. _this._renderId = 0;
  25010. _this._mesh = mesh;
  25011. _this._renderingMesh = renderingMesh || mesh;
  25012. mesh.subMeshes.push(_this);
  25013. _this._trianglePlanes = [];
  25014. _this._id = mesh.subMeshes.length - 1;
  25015. if (createBoundingBox) {
  25016. _this.refreshBoundingInfo();
  25017. mesh.computeWorldMatrix(true);
  25018. }
  25019. return _this;
  25020. }
  25021. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25022. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25023. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25024. };
  25025. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25026. get: function () {
  25027. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25028. },
  25029. enumerable: true,
  25030. configurable: true
  25031. });
  25032. /**
  25033. * Returns the submesh BoudingInfo object.
  25034. */
  25035. SubMesh.prototype.getBoundingInfo = function () {
  25036. if (this.IsGlobal) {
  25037. return this._mesh.getBoundingInfo();
  25038. }
  25039. return this._boundingInfo;
  25040. };
  25041. /**
  25042. * Sets the submesh BoundingInfo.
  25043. * Return the SubMesh.
  25044. */
  25045. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25046. this._boundingInfo = boundingInfo;
  25047. return this;
  25048. };
  25049. /**
  25050. * Returns the mesh of the current submesh.
  25051. */
  25052. SubMesh.prototype.getMesh = function () {
  25053. return this._mesh;
  25054. };
  25055. /**
  25056. * Returns the rendering mesh of the submesh.
  25057. */
  25058. SubMesh.prototype.getRenderingMesh = function () {
  25059. return this._renderingMesh;
  25060. };
  25061. /**
  25062. * Returns the submesh material.
  25063. */
  25064. SubMesh.prototype.getMaterial = function () {
  25065. var rootMaterial = this._renderingMesh.material;
  25066. if (rootMaterial && rootMaterial.getSubMaterial) {
  25067. var multiMaterial = rootMaterial;
  25068. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25069. if (this._currentMaterial !== effectiveMaterial) {
  25070. this._currentMaterial = effectiveMaterial;
  25071. this._materialDefines = null;
  25072. }
  25073. return effectiveMaterial;
  25074. }
  25075. if (!rootMaterial) {
  25076. return this._mesh.getScene().defaultMaterial;
  25077. }
  25078. return rootMaterial;
  25079. };
  25080. // Methods
  25081. /**
  25082. * Sets a new updated BoundingInfo object to the submesh.
  25083. * Returns the SubMesh.
  25084. */
  25085. SubMesh.prototype.refreshBoundingInfo = function () {
  25086. this._lastColliderWorldVertices = null;
  25087. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25088. return this;
  25089. }
  25090. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25091. if (!data) {
  25092. this._boundingInfo = this._mesh._boundingInfo;
  25093. return this;
  25094. }
  25095. var indices = this._renderingMesh.getIndices();
  25096. var extend;
  25097. //is this the only submesh?
  25098. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25099. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25100. if (!boundingInfo) {
  25101. return this;
  25102. }
  25103. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25104. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25105. }
  25106. else {
  25107. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25108. }
  25109. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25110. return this;
  25111. };
  25112. SubMesh.prototype._checkCollision = function (collider) {
  25113. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25114. if (!boundingInfo) {
  25115. return false;
  25116. }
  25117. return boundingInfo._checkCollision(collider);
  25118. };
  25119. /**
  25120. * Updates the submesh BoundingInfo.
  25121. * Returns the Submesh.
  25122. */
  25123. SubMesh.prototype.updateBoundingInfo = function (world) {
  25124. var boundingInfo = this.getBoundingInfo();
  25125. if (!boundingInfo) {
  25126. this.refreshBoundingInfo();
  25127. }
  25128. boundingInfo.update(world);
  25129. return this;
  25130. };
  25131. /**
  25132. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25133. * Boolean returned.
  25134. */
  25135. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25136. var boundingInfo = this.getBoundingInfo();
  25137. if (!boundingInfo) {
  25138. return false;
  25139. }
  25140. return boundingInfo.isInFrustum(frustumPlanes);
  25141. };
  25142. /**
  25143. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25144. * Boolean returned.
  25145. */
  25146. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25147. var boundingInfo = this.getBoundingInfo();
  25148. if (!boundingInfo) {
  25149. return false;
  25150. }
  25151. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25152. };
  25153. /**
  25154. * Renders the submesh.
  25155. * Returns it.
  25156. */
  25157. SubMesh.prototype.render = function (enableAlphaMode) {
  25158. this._renderingMesh.render(this, enableAlphaMode);
  25159. return this;
  25160. };
  25161. /**
  25162. * Returns a new Index Buffer.
  25163. * Type returned : WebGLBuffer.
  25164. */
  25165. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25166. if (!this._linesIndexBuffer) {
  25167. var linesIndices = [];
  25168. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25169. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25170. }
  25171. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25172. this.linesIndexCount = linesIndices.length;
  25173. }
  25174. return this._linesIndexBuffer;
  25175. };
  25176. /**
  25177. * True is the passed Ray intersects the submesh bounding box.
  25178. * Boolean returned.
  25179. */
  25180. SubMesh.prototype.canIntersects = function (ray) {
  25181. var boundingInfo = this.getBoundingInfo();
  25182. if (!boundingInfo) {
  25183. return false;
  25184. }
  25185. return ray.intersectsBox(boundingInfo.boundingBox);
  25186. };
  25187. /**
  25188. * Returns an object IntersectionInfo.
  25189. */
  25190. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25191. var intersectInfo = null;
  25192. // LineMesh first as it's also a Mesh...
  25193. if (this._mesh instanceof BABYLON.LinesMesh) {
  25194. var lineMesh = this._mesh;
  25195. // Line test
  25196. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25197. var p0 = positions[indices[index]];
  25198. var p1 = positions[indices[index + 1]];
  25199. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25200. if (length < 0) {
  25201. continue;
  25202. }
  25203. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25204. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25205. if (fastCheck) {
  25206. break;
  25207. }
  25208. }
  25209. }
  25210. }
  25211. else {
  25212. // Triangles test
  25213. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25214. var p0 = positions[indices[index]];
  25215. var p1 = positions[indices[index + 1]];
  25216. var p2 = positions[indices[index + 2]];
  25217. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25218. if (currentIntersectInfo) {
  25219. if (currentIntersectInfo.distance < 0) {
  25220. continue;
  25221. }
  25222. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25223. intersectInfo = currentIntersectInfo;
  25224. intersectInfo.faceId = index / 3;
  25225. if (fastCheck) {
  25226. break;
  25227. }
  25228. }
  25229. }
  25230. }
  25231. }
  25232. return intersectInfo;
  25233. };
  25234. SubMesh.prototype._rebuild = function () {
  25235. if (this._linesIndexBuffer) {
  25236. this._linesIndexBuffer = null;
  25237. }
  25238. };
  25239. // Clone
  25240. /**
  25241. * Creates a new Submesh from the passed Mesh.
  25242. */
  25243. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25244. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25245. if (!this.IsGlobal) {
  25246. var boundingInfo = this.getBoundingInfo();
  25247. if (!boundingInfo) {
  25248. return result;
  25249. }
  25250. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25251. }
  25252. return result;
  25253. };
  25254. // Dispose
  25255. /**
  25256. * Disposes the Submesh.
  25257. * Returns nothing.
  25258. */
  25259. SubMesh.prototype.dispose = function () {
  25260. if (this._linesIndexBuffer) {
  25261. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25262. this._linesIndexBuffer = null;
  25263. }
  25264. // Remove from mesh
  25265. var index = this._mesh.subMeshes.indexOf(this);
  25266. this._mesh.subMeshes.splice(index, 1);
  25267. };
  25268. // Statics
  25269. /**
  25270. * Creates a new Submesh from the passed parameters :
  25271. * - materialIndex (integer) : the index of the main mesh material.
  25272. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25273. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25274. * - mesh (Mesh) : the main mesh to create the submesh from.
  25275. * - renderingMesh (optional Mesh) : rendering mesh.
  25276. */
  25277. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25278. var minVertexIndex = Number.MAX_VALUE;
  25279. var maxVertexIndex = -Number.MAX_VALUE;
  25280. renderingMesh = (renderingMesh || mesh);
  25281. var indices = renderingMesh.getIndices();
  25282. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25283. var vertexIndex = indices[index];
  25284. if (vertexIndex < minVertexIndex)
  25285. minVertexIndex = vertexIndex;
  25286. if (vertexIndex > maxVertexIndex)
  25287. maxVertexIndex = vertexIndex;
  25288. }
  25289. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25290. };
  25291. return SubMesh;
  25292. }(BaseSubMesh));
  25293. BABYLON.SubMesh = SubMesh;
  25294. })(BABYLON || (BABYLON = {}));
  25295. //# sourceMappingURL=babylon.subMesh.js.map
  25296. var BABYLON;
  25297. (function (BABYLON) {
  25298. var EffectFallbacks = /** @class */ (function () {
  25299. function EffectFallbacks() {
  25300. this._defines = {};
  25301. this._currentRank = 32;
  25302. this._maxRank = -1;
  25303. }
  25304. EffectFallbacks.prototype.unBindMesh = function () {
  25305. this._mesh = null;
  25306. };
  25307. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25308. if (!this._defines[rank]) {
  25309. if (rank < this._currentRank) {
  25310. this._currentRank = rank;
  25311. }
  25312. if (rank > this._maxRank) {
  25313. this._maxRank = rank;
  25314. }
  25315. this._defines[rank] = new Array();
  25316. }
  25317. this._defines[rank].push(define);
  25318. };
  25319. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25320. this._meshRank = rank;
  25321. this._mesh = mesh;
  25322. if (rank < this._currentRank) {
  25323. this._currentRank = rank;
  25324. }
  25325. if (rank > this._maxRank) {
  25326. this._maxRank = rank;
  25327. }
  25328. };
  25329. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25330. get: function () {
  25331. return this._currentRank <= this._maxRank;
  25332. },
  25333. enumerable: true,
  25334. configurable: true
  25335. });
  25336. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25337. // First we try to switch to CPU skinning
  25338. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25339. this._mesh.computeBonesUsingShaders = false;
  25340. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25341. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25342. var scene = this._mesh.getScene();
  25343. for (var index = 0; index < scene.meshes.length; index++) {
  25344. var otherMesh = scene.meshes[index];
  25345. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25346. otherMesh.computeBonesUsingShaders = false;
  25347. }
  25348. }
  25349. }
  25350. else {
  25351. var currentFallbacks = this._defines[this._currentRank];
  25352. if (currentFallbacks) {
  25353. for (var index = 0; index < currentFallbacks.length; index++) {
  25354. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25355. }
  25356. }
  25357. this._currentRank++;
  25358. }
  25359. return currentDefines;
  25360. };
  25361. return EffectFallbacks;
  25362. }());
  25363. BABYLON.EffectFallbacks = EffectFallbacks;
  25364. var EffectCreationOptions = /** @class */ (function () {
  25365. function EffectCreationOptions() {
  25366. }
  25367. return EffectCreationOptions;
  25368. }());
  25369. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25370. var Effect = /** @class */ (function () {
  25371. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25372. if (samplers === void 0) { samplers = null; }
  25373. if (defines === void 0) { defines = null; }
  25374. if (fallbacks === void 0) { fallbacks = null; }
  25375. if (onCompiled === void 0) { onCompiled = null; }
  25376. if (onError === void 0) { onError = null; }
  25377. var _this = this;
  25378. this.uniqueId = 0;
  25379. this.onCompileObservable = new BABYLON.Observable();
  25380. this.onErrorObservable = new BABYLON.Observable();
  25381. this.onBindObservable = new BABYLON.Observable();
  25382. this._uniformBuffersNames = {};
  25383. this._isReady = false;
  25384. this._compilationError = "";
  25385. this.name = baseName;
  25386. if (attributesNamesOrOptions.attributes) {
  25387. var options = attributesNamesOrOptions;
  25388. this._engine = uniformsNamesOrEngine;
  25389. this._attributesNames = options.attributes;
  25390. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25391. this._samplers = options.samplers;
  25392. this.defines = options.defines;
  25393. this.onError = options.onError;
  25394. this.onCompiled = options.onCompiled;
  25395. this._fallbacks = options.fallbacks;
  25396. this._indexParameters = options.indexParameters;
  25397. if (options.uniformBuffersNames) {
  25398. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25399. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25400. }
  25401. }
  25402. }
  25403. else {
  25404. this._engine = engine;
  25405. this.defines = defines;
  25406. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25407. this._samplers = samplers;
  25408. this._attributesNames = attributesNamesOrOptions;
  25409. this.onError = onError;
  25410. this.onCompiled = onCompiled;
  25411. this._indexParameters = indexParameters;
  25412. this._fallbacks = fallbacks;
  25413. }
  25414. this.uniqueId = Effect._uniqueIdSeed++;
  25415. var vertexSource;
  25416. var fragmentSource;
  25417. if (baseName.vertexElement) {
  25418. vertexSource = document.getElementById(baseName.vertexElement);
  25419. if (!vertexSource) {
  25420. vertexSource = baseName.vertexElement;
  25421. }
  25422. }
  25423. else {
  25424. vertexSource = baseName.vertex || baseName;
  25425. }
  25426. if (baseName.fragmentElement) {
  25427. fragmentSource = document.getElementById(baseName.fragmentElement);
  25428. if (!fragmentSource) {
  25429. fragmentSource = baseName.fragmentElement;
  25430. }
  25431. }
  25432. else {
  25433. fragmentSource = baseName.fragment || baseName;
  25434. }
  25435. this._loadVertexShader(vertexSource, function (vertexCode) {
  25436. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25437. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25438. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25439. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25440. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25441. if (baseName) {
  25442. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25443. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25444. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25445. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25446. }
  25447. else {
  25448. _this._vertexSourceCode = migratedVertexCode;
  25449. _this._fragmentSourceCode = migratedFragmentCode;
  25450. }
  25451. _this._prepareEffect();
  25452. });
  25453. });
  25454. });
  25455. });
  25456. });
  25457. });
  25458. }
  25459. Object.defineProperty(Effect.prototype, "key", {
  25460. get: function () {
  25461. return this._key;
  25462. },
  25463. enumerable: true,
  25464. configurable: true
  25465. });
  25466. // Properties
  25467. Effect.prototype.isReady = function () {
  25468. return this._isReady;
  25469. };
  25470. Effect.prototype.getEngine = function () {
  25471. return this._engine;
  25472. };
  25473. Effect.prototype.getProgram = function () {
  25474. return this._program;
  25475. };
  25476. Effect.prototype.getAttributesNames = function () {
  25477. return this._attributesNames;
  25478. };
  25479. Effect.prototype.getAttributeLocation = function (index) {
  25480. return this._attributes[index];
  25481. };
  25482. Effect.prototype.getAttributeLocationByName = function (name) {
  25483. var index = this._attributesNames.indexOf(name);
  25484. return this._attributes[index];
  25485. };
  25486. Effect.prototype.getAttributesCount = function () {
  25487. return this._attributes.length;
  25488. };
  25489. Effect.prototype.getUniformIndex = function (uniformName) {
  25490. return this._uniformsNames.indexOf(uniformName);
  25491. };
  25492. Effect.prototype.getUniform = function (uniformName) {
  25493. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25494. };
  25495. Effect.prototype.getSamplers = function () {
  25496. return this._samplers;
  25497. };
  25498. Effect.prototype.getCompilationError = function () {
  25499. return this._compilationError;
  25500. };
  25501. // Methods
  25502. Effect.prototype.executeWhenCompiled = function (func) {
  25503. if (this.isReady()) {
  25504. func(this);
  25505. return;
  25506. }
  25507. this.onCompileObservable.add(function (effect) {
  25508. func(effect);
  25509. });
  25510. };
  25511. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25512. if (BABYLON.Tools.IsWindowObjectExist()) {
  25513. // DOM element ?
  25514. if (vertex instanceof HTMLElement) {
  25515. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25516. callback(vertexCode);
  25517. return;
  25518. }
  25519. }
  25520. // Base64 encoded ?
  25521. if (vertex.substr(0, 7) === "base64:") {
  25522. var vertexBinary = window.atob(vertex.substr(7));
  25523. callback(vertexBinary);
  25524. return;
  25525. }
  25526. // Is in local store ?
  25527. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25528. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25529. return;
  25530. }
  25531. var vertexShaderUrl;
  25532. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25533. vertexShaderUrl = vertex;
  25534. }
  25535. else {
  25536. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25537. }
  25538. // Vertex shader
  25539. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25540. };
  25541. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25542. if (BABYLON.Tools.IsWindowObjectExist()) {
  25543. // DOM element ?
  25544. if (fragment instanceof HTMLElement) {
  25545. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25546. callback(fragmentCode);
  25547. return;
  25548. }
  25549. }
  25550. // Base64 encoded ?
  25551. if (fragment.substr(0, 7) === "base64:") {
  25552. var fragmentBinary = window.atob(fragment.substr(7));
  25553. callback(fragmentBinary);
  25554. return;
  25555. }
  25556. // Is in local store ?
  25557. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25558. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25559. return;
  25560. }
  25561. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25562. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25563. return;
  25564. }
  25565. var fragmentShaderUrl;
  25566. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25567. fragmentShaderUrl = fragment;
  25568. }
  25569. else {
  25570. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25571. }
  25572. // Fragment shader
  25573. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25574. };
  25575. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25576. // Rebuild shaders source code
  25577. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25578. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25579. vertexCode = prefix + vertexCode;
  25580. fragmentCode = prefix + fragmentCode;
  25581. // Number lines of shaders source code
  25582. var i = 2;
  25583. var regex = /\n/gm;
  25584. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25585. i = 2;
  25586. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25587. // Dump shaders name and formatted source code
  25588. if (this.name.vertexElement) {
  25589. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25590. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25591. }
  25592. else if (this.name.vertex) {
  25593. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25594. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25595. }
  25596. else {
  25597. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25598. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25599. }
  25600. };
  25601. ;
  25602. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25603. var preparedSourceCode = this._processPrecision(sourceCode);
  25604. if (this._engine.webGLVersion == 1) {
  25605. callback(preparedSourceCode);
  25606. return;
  25607. }
  25608. // Already converted
  25609. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25610. callback(preparedSourceCode.replace("#version 300 es", ""));
  25611. return;
  25612. }
  25613. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25614. // Remove extensions
  25615. // #extension GL_OES_standard_derivatives : enable
  25616. // #extension GL_EXT_shader_texture_lod : enable
  25617. // #extension GL_EXT_frag_depth : enable
  25618. // #extension GL_EXT_draw_buffers : require
  25619. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25620. var result = preparedSourceCode.replace(regex, "");
  25621. // Migrate to GLSL v300
  25622. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25623. result = result.replace(/attribute[ \t]/g, "in ");
  25624. result = result.replace(/[ \t]attribute/g, " in");
  25625. if (isFragment) {
  25626. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25627. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25628. result = result.replace(/texture2D\s*\(/g, "texture(");
  25629. result = result.replace(/textureCube\s*\(/g, "texture(");
  25630. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25631. result = result.replace(/gl_FragColor/g, "glFragColor");
  25632. result = result.replace(/gl_FragData/g, "glFragData");
  25633. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25634. }
  25635. callback(result);
  25636. };
  25637. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25638. var _this = this;
  25639. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25640. var match = regex.exec(sourceCode);
  25641. var returnValue = new String(sourceCode);
  25642. while (match != null) {
  25643. var includeFile = match[1];
  25644. // Uniform declaration
  25645. if (includeFile.indexOf("__decl__") !== -1) {
  25646. includeFile = includeFile.replace(/__decl__/, "");
  25647. if (this._engine.supportsUniformBuffers) {
  25648. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25649. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25650. }
  25651. includeFile = includeFile + "Declaration";
  25652. }
  25653. if (Effect.IncludesShadersStore[includeFile]) {
  25654. // Substitution
  25655. var includeContent = Effect.IncludesShadersStore[includeFile];
  25656. if (match[2]) {
  25657. var splits = match[3].split(",");
  25658. for (var index = 0; index < splits.length; index += 2) {
  25659. var source = new RegExp(splits[index], "g");
  25660. var dest = splits[index + 1];
  25661. includeContent = includeContent.replace(source, dest);
  25662. }
  25663. }
  25664. if (match[4]) {
  25665. var indexString = match[5];
  25666. if (indexString.indexOf("..") !== -1) {
  25667. var indexSplits = indexString.split("..");
  25668. var minIndex = parseInt(indexSplits[0]);
  25669. var maxIndex = parseInt(indexSplits[1]);
  25670. var sourceIncludeContent = includeContent.slice(0);
  25671. includeContent = "";
  25672. if (isNaN(maxIndex)) {
  25673. maxIndex = this._indexParameters[indexSplits[1]];
  25674. }
  25675. for (var i = minIndex; i < maxIndex; i++) {
  25676. if (!this._engine.supportsUniformBuffers) {
  25677. // Ubo replacement
  25678. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25679. return p1 + "{X}";
  25680. });
  25681. }
  25682. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  25683. }
  25684. }
  25685. else {
  25686. if (!this._engine.supportsUniformBuffers) {
  25687. // Ubo replacement
  25688. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25689. return p1 + "{X}";
  25690. });
  25691. }
  25692. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25693. }
  25694. }
  25695. // Replace
  25696. returnValue = returnValue.replace(match[0], includeContent);
  25697. }
  25698. else {
  25699. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25700. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25701. Effect.IncludesShadersStore[includeFile] = fileContent;
  25702. _this._processIncludes(returnValue, callback);
  25703. });
  25704. return;
  25705. }
  25706. match = regex.exec(sourceCode);
  25707. }
  25708. callback(returnValue);
  25709. };
  25710. Effect.prototype._processPrecision = function (source) {
  25711. if (source.indexOf("precision highp float") === -1) {
  25712. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25713. source = "precision mediump float;\n" + source;
  25714. }
  25715. else {
  25716. source = "precision highp float;\n" + source;
  25717. }
  25718. }
  25719. else {
  25720. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25721. source = source.replace("precision highp float", "precision mediump float");
  25722. }
  25723. }
  25724. return source;
  25725. };
  25726. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  25727. var _this = this;
  25728. this._isReady = false;
  25729. this._vertexSourceCodeOverride = vertexSourceCode;
  25730. this._fragmentSourceCodeOverride = fragmentSourceCode;
  25731. this.onError = function (effect, error) {
  25732. if (onError) {
  25733. onError(error);
  25734. }
  25735. };
  25736. this.onCompiled = function () {
  25737. var scenes = _this.getEngine().scenes;
  25738. for (var i = 0; i < scenes.length; i++) {
  25739. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25740. }
  25741. if (onCompiled) {
  25742. onCompiled(_this._program);
  25743. }
  25744. };
  25745. this._fallbacks = null;
  25746. this._prepareEffect();
  25747. };
  25748. Effect.prototype._prepareEffect = function () {
  25749. var attributesNames = this._attributesNames;
  25750. var defines = this.defines;
  25751. var fallbacks = this._fallbacks;
  25752. this._valueCache = {};
  25753. var previousProgram = this._program;
  25754. try {
  25755. var engine = this._engine;
  25756. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  25757. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride);
  25758. }
  25759. else {
  25760. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25761. }
  25762. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  25763. if (engine.webGLVersion > 1) {
  25764. for (var name in this._uniformBuffersNames) {
  25765. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  25766. }
  25767. }
  25768. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25769. this._attributes = engine.getAttributes(this._program, attributesNames);
  25770. var index;
  25771. for (index = 0; index < this._samplers.length; index++) {
  25772. var sampler = this.getUniform(this._samplers[index]);
  25773. if (sampler == null) {
  25774. this._samplers.splice(index, 1);
  25775. index--;
  25776. }
  25777. }
  25778. engine.bindSamplers(this);
  25779. this._compilationError = "";
  25780. this._isReady = true;
  25781. if (this.onCompiled) {
  25782. this.onCompiled(this);
  25783. }
  25784. this.onCompileObservable.notifyObservers(this);
  25785. this.onCompileObservable.clear();
  25786. // Unbind mesh reference in fallbacks
  25787. if (this._fallbacks) {
  25788. this._fallbacks.unBindMesh();
  25789. }
  25790. if (previousProgram) {
  25791. this.getEngine()._deleteProgram(previousProgram);
  25792. }
  25793. }
  25794. catch (e) {
  25795. this._compilationError = e.message;
  25796. // Let's go through fallbacks then
  25797. BABYLON.Tools.Error("Unable to compile effect:");
  25798. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  25799. return " " + uniform;
  25800. }));
  25801. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  25802. return " " + attribute;
  25803. }));
  25804. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25805. BABYLON.Tools.Error("Error: " + this._compilationError);
  25806. if (previousProgram) {
  25807. this._program = previousProgram;
  25808. this._isReady = true;
  25809. if (this.onError) {
  25810. this.onError(this, this._compilationError);
  25811. }
  25812. this.onErrorObservable.notifyObservers(this);
  25813. }
  25814. if (fallbacks && fallbacks.isMoreFallbacks) {
  25815. BABYLON.Tools.Error("Trying next fallback.");
  25816. this.defines = fallbacks.reduce(this.defines);
  25817. this._prepareEffect();
  25818. }
  25819. else {
  25820. if (this.onError) {
  25821. this.onError(this, this._compilationError);
  25822. }
  25823. this.onErrorObservable.notifyObservers(this);
  25824. this.onErrorObservable.clear();
  25825. // Unbind mesh reference in fallbacks
  25826. if (this._fallbacks) {
  25827. this._fallbacks.unBindMesh();
  25828. }
  25829. }
  25830. }
  25831. };
  25832. Object.defineProperty(Effect.prototype, "isSupported", {
  25833. get: function () {
  25834. return this._compilationError === "";
  25835. },
  25836. enumerable: true,
  25837. configurable: true
  25838. });
  25839. Effect.prototype._bindTexture = function (channel, texture) {
  25840. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25841. };
  25842. Effect.prototype.setTexture = function (channel, texture) {
  25843. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25844. };
  25845. Effect.prototype.setTextureArray = function (channel, textures) {
  25846. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25847. var initialPos = this._samplers.indexOf(channel);
  25848. for (var index = 1; index < textures.length; index++) {
  25849. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25850. }
  25851. }
  25852. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25853. };
  25854. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25855. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25856. };
  25857. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25858. var cache = this._valueCache[uniformName];
  25859. var flag = matrix.updateFlag;
  25860. if (cache !== undefined && cache === flag) {
  25861. return false;
  25862. }
  25863. this._valueCache[uniformName] = flag;
  25864. return true;
  25865. };
  25866. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25867. var cache = this._valueCache[uniformName];
  25868. if (!cache) {
  25869. cache = [x, y];
  25870. this._valueCache[uniformName] = cache;
  25871. return true;
  25872. }
  25873. var changed = false;
  25874. if (cache[0] !== x) {
  25875. cache[0] = x;
  25876. changed = true;
  25877. }
  25878. if (cache[1] !== y) {
  25879. cache[1] = y;
  25880. changed = true;
  25881. }
  25882. return changed;
  25883. };
  25884. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25885. var cache = this._valueCache[uniformName];
  25886. if (!cache) {
  25887. cache = [x, y, z];
  25888. this._valueCache[uniformName] = cache;
  25889. return true;
  25890. }
  25891. var changed = false;
  25892. if (cache[0] !== x) {
  25893. cache[0] = x;
  25894. changed = true;
  25895. }
  25896. if (cache[1] !== y) {
  25897. cache[1] = y;
  25898. changed = true;
  25899. }
  25900. if (cache[2] !== z) {
  25901. cache[2] = z;
  25902. changed = true;
  25903. }
  25904. return changed;
  25905. };
  25906. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25907. var cache = this._valueCache[uniformName];
  25908. if (!cache) {
  25909. cache = [x, y, z, w];
  25910. this._valueCache[uniformName] = cache;
  25911. return true;
  25912. }
  25913. var changed = false;
  25914. if (cache[0] !== x) {
  25915. cache[0] = x;
  25916. changed = true;
  25917. }
  25918. if (cache[1] !== y) {
  25919. cache[1] = y;
  25920. changed = true;
  25921. }
  25922. if (cache[2] !== z) {
  25923. cache[2] = z;
  25924. changed = true;
  25925. }
  25926. if (cache[3] !== w) {
  25927. cache[3] = w;
  25928. changed = true;
  25929. }
  25930. return changed;
  25931. };
  25932. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  25933. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  25934. return;
  25935. }
  25936. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  25937. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  25938. };
  25939. Effect.prototype.bindUniformBlock = function (blockName, index) {
  25940. this._engine.bindUniformBlock(this._program, blockName, index);
  25941. };
  25942. Effect.prototype.setIntArray = function (uniformName, array) {
  25943. this._valueCache[uniformName] = null;
  25944. this._engine.setIntArray(this.getUniform(uniformName), array);
  25945. return this;
  25946. };
  25947. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25948. this._valueCache[uniformName] = null;
  25949. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25950. return this;
  25951. };
  25952. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25953. this._valueCache[uniformName] = null;
  25954. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25955. return this;
  25956. };
  25957. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25958. this._valueCache[uniformName] = null;
  25959. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25960. return this;
  25961. };
  25962. Effect.prototype.setFloatArray = function (uniformName, array) {
  25963. this._valueCache[uniformName] = null;
  25964. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25965. return this;
  25966. };
  25967. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25968. this._valueCache[uniformName] = null;
  25969. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25970. return this;
  25971. };
  25972. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25973. this._valueCache[uniformName] = null;
  25974. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25975. return this;
  25976. };
  25977. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25978. this._valueCache[uniformName] = null;
  25979. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25980. return this;
  25981. };
  25982. Effect.prototype.setArray = function (uniformName, array) {
  25983. this._valueCache[uniformName] = null;
  25984. this._engine.setArray(this.getUniform(uniformName), array);
  25985. return this;
  25986. };
  25987. Effect.prototype.setArray2 = function (uniformName, array) {
  25988. this._valueCache[uniformName] = null;
  25989. this._engine.setArray2(this.getUniform(uniformName), array);
  25990. return this;
  25991. };
  25992. Effect.prototype.setArray3 = function (uniformName, array) {
  25993. this._valueCache[uniformName] = null;
  25994. this._engine.setArray3(this.getUniform(uniformName), array);
  25995. return this;
  25996. };
  25997. Effect.prototype.setArray4 = function (uniformName, array) {
  25998. this._valueCache[uniformName] = null;
  25999. this._engine.setArray4(this.getUniform(uniformName), array);
  26000. return this;
  26001. };
  26002. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26003. if (!matrices) {
  26004. return this;
  26005. }
  26006. this._valueCache[uniformName] = null;
  26007. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26008. return this;
  26009. };
  26010. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26011. if (this._cacheMatrix(uniformName, matrix)) {
  26012. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26013. }
  26014. return this;
  26015. };
  26016. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26017. this._valueCache[uniformName] = null;
  26018. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26019. return this;
  26020. };
  26021. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26022. this._valueCache[uniformName] = null;
  26023. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26024. return this;
  26025. };
  26026. Effect.prototype.setFloat = function (uniformName, value) {
  26027. var cache = this._valueCache[uniformName];
  26028. if (cache !== undefined && cache === value)
  26029. return this;
  26030. this._valueCache[uniformName] = value;
  26031. this._engine.setFloat(this.getUniform(uniformName), value);
  26032. return this;
  26033. };
  26034. Effect.prototype.setBool = function (uniformName, bool) {
  26035. var cache = this._valueCache[uniformName];
  26036. if (cache !== undefined && cache === bool)
  26037. return this;
  26038. this._valueCache[uniformName] = bool;
  26039. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26040. return this;
  26041. };
  26042. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26043. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26044. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26045. }
  26046. return this;
  26047. };
  26048. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26049. if (this._cacheFloat2(uniformName, x, y)) {
  26050. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26051. }
  26052. return this;
  26053. };
  26054. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26055. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26056. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26057. }
  26058. return this;
  26059. };
  26060. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26061. if (this._cacheFloat3(uniformName, x, y, z)) {
  26062. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26063. }
  26064. return this;
  26065. };
  26066. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26067. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26068. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26069. }
  26070. return this;
  26071. };
  26072. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26073. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26074. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26075. }
  26076. return this;
  26077. };
  26078. Effect.prototype.setColor3 = function (uniformName, color3) {
  26079. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26080. this._engine.setColor3(this.getUniform(uniformName), color3);
  26081. }
  26082. return this;
  26083. };
  26084. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26085. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26086. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26087. }
  26088. return this;
  26089. };
  26090. Effect.ResetCache = function () {
  26091. Effect._baseCache = {};
  26092. };
  26093. Effect._uniqueIdSeed = 0;
  26094. Effect._baseCache = {};
  26095. // Statics
  26096. Effect.ShadersStore = {};
  26097. Effect.IncludesShadersStore = {};
  26098. return Effect;
  26099. }());
  26100. BABYLON.Effect = Effect;
  26101. })(BABYLON || (BABYLON = {}));
  26102. //# sourceMappingURL=babylon.effect.js.map
  26103. var BABYLON;
  26104. (function (BABYLON) {
  26105. var MaterialHelper = /** @class */ (function () {
  26106. function MaterialHelper() {
  26107. }
  26108. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26109. defines._needUVs = true;
  26110. defines[key] = true;
  26111. if (texture.getTextureMatrix().isIdentity(true)) {
  26112. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26113. if (texture.coordinatesIndex === 0) {
  26114. defines["MAINUV1"] = true;
  26115. }
  26116. else {
  26117. defines["MAINUV2"] = true;
  26118. }
  26119. }
  26120. else {
  26121. defines[key + "DIRECTUV"] = 0;
  26122. }
  26123. };
  26124. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26125. var matrix = texture.getTextureMatrix();
  26126. if (!matrix.isIdentity(true)) {
  26127. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26128. }
  26129. };
  26130. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26131. if (defines._areMiscDirty) {
  26132. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26133. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26134. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26135. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26136. }
  26137. };
  26138. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26139. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26140. var changed = false;
  26141. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26142. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26143. changed = true;
  26144. }
  26145. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26146. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26147. changed = true;
  26148. }
  26149. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26150. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26151. changed = true;
  26152. }
  26153. if (defines["INSTANCES"] !== useInstances) {
  26154. defines["INSTANCES"] = useInstances;
  26155. changed = true;
  26156. }
  26157. if (changed) {
  26158. defines.markAsUnprocessed();
  26159. }
  26160. };
  26161. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  26162. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26163. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26164. return false;
  26165. }
  26166. defines._normals = defines._needNormals;
  26167. defines._uvs = defines._needUVs;
  26168. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26169. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26170. defines["TANGENT"] = true;
  26171. }
  26172. if (defines._needUVs) {
  26173. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26174. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26175. }
  26176. else {
  26177. defines["UV1"] = false;
  26178. defines["UV2"] = false;
  26179. }
  26180. if (useVertexColor) {
  26181. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26182. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  26183. }
  26184. if (useBones) {
  26185. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26186. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26187. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26188. }
  26189. else {
  26190. defines["NUM_BONE_INFLUENCERS"] = 0;
  26191. defines["BonesPerMesh"] = 0;
  26192. }
  26193. }
  26194. if (useMorphTargets) {
  26195. var manager = mesh.morphTargetManager;
  26196. if (manager) {
  26197. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26198. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26199. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26200. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26201. }
  26202. else {
  26203. defines["MORPHTARGETS_TANGENT"] = false;
  26204. defines["MORPHTARGETS_NORMAL"] = false;
  26205. defines["MORPHTARGETS"] = false;
  26206. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26207. }
  26208. }
  26209. return true;
  26210. };
  26211. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26212. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26213. if (disableLighting === void 0) { disableLighting = false; }
  26214. if (!defines._areLightsDirty) {
  26215. return defines._needNormals;
  26216. }
  26217. var lightIndex = 0;
  26218. var needNormals = false;
  26219. var needRebuild = false;
  26220. var lightmapMode = false;
  26221. var shadowEnabled = false;
  26222. var specularEnabled = false;
  26223. if (scene.lightsEnabled && !disableLighting) {
  26224. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26225. var light = _a[_i];
  26226. needNormals = true;
  26227. if (defines["LIGHT" + lightIndex] === undefined) {
  26228. needRebuild = true;
  26229. }
  26230. defines["LIGHT" + lightIndex] = true;
  26231. defines["SPOTLIGHT" + lightIndex] = false;
  26232. defines["HEMILIGHT" + lightIndex] = false;
  26233. defines["POINTLIGHT" + lightIndex] = false;
  26234. defines["DIRLIGHT" + lightIndex] = false;
  26235. var type;
  26236. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26237. type = "SPOTLIGHT" + lightIndex;
  26238. }
  26239. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26240. type = "HEMILIGHT" + lightIndex;
  26241. }
  26242. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26243. type = "POINTLIGHT" + lightIndex;
  26244. }
  26245. else {
  26246. type = "DIRLIGHT" + lightIndex;
  26247. }
  26248. defines[type] = true;
  26249. // Specular
  26250. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26251. specularEnabled = true;
  26252. }
  26253. // Shadows
  26254. defines["SHADOW" + lightIndex] = false;
  26255. defines["SHADOWPCF" + lightIndex] = false;
  26256. defines["SHADOWESM" + lightIndex] = false;
  26257. defines["SHADOWCUBE" + lightIndex] = false;
  26258. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26259. var shadowGenerator = light.getShadowGenerator();
  26260. if (shadowGenerator) {
  26261. shadowEnabled = true;
  26262. shadowGenerator.prepareDefines(defines, lightIndex);
  26263. }
  26264. }
  26265. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26266. lightmapMode = true;
  26267. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26268. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26269. }
  26270. else {
  26271. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26272. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26273. }
  26274. lightIndex++;
  26275. if (lightIndex === maxSimultaneousLights)
  26276. break;
  26277. }
  26278. }
  26279. defines["SPECULARTERM"] = specularEnabled;
  26280. defines["SHADOWS"] = shadowEnabled;
  26281. // Resetting all other lights if any
  26282. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26283. if (defines["LIGHT" + index] !== undefined) {
  26284. defines["LIGHT" + index] = false;
  26285. defines["HEMILIGHT" + lightIndex] = false;
  26286. defines["POINTLIGHT" + lightIndex] = false;
  26287. defines["DIRLIGHT" + lightIndex] = false;
  26288. defines["SPOTLIGHT" + lightIndex] = false;
  26289. defines["SHADOW" + lightIndex] = false;
  26290. }
  26291. }
  26292. var caps = scene.getEngine().getCaps();
  26293. if (defines["SHADOWFLOAT"] === undefined) {
  26294. needRebuild = true;
  26295. }
  26296. defines["SHADOWFLOAT"] = shadowEnabled &&
  26297. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26298. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26299. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26300. if (needRebuild) {
  26301. defines.rebuild();
  26302. }
  26303. return needNormals;
  26304. };
  26305. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26306. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26307. var uniformsList;
  26308. var uniformBuffersList = null;
  26309. if (uniformsListOrOptions.uniformsNames) {
  26310. var options = uniformsListOrOptions;
  26311. uniformsList = options.uniformsNames;
  26312. uniformBuffersList = options.uniformBuffersNames;
  26313. samplersList = options.samplers;
  26314. defines = options.defines;
  26315. maxSimultaneousLights = options.maxSimultaneousLights;
  26316. }
  26317. else {
  26318. uniformsList = uniformsListOrOptions;
  26319. if (!samplersList) {
  26320. samplersList = [];
  26321. }
  26322. }
  26323. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26324. if (!defines["LIGHT" + lightIndex]) {
  26325. break;
  26326. }
  26327. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26328. if (uniformBuffersList) {
  26329. uniformBuffersList.push("Light" + lightIndex);
  26330. }
  26331. samplersList.push("shadowSampler" + lightIndex);
  26332. }
  26333. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26334. uniformsList.push("morphTargetInfluences");
  26335. }
  26336. };
  26337. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26338. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26339. if (!defines["SHADOWS"]) {
  26340. return;
  26341. }
  26342. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26343. if (!defines["LIGHT" + lightIndex]) {
  26344. break;
  26345. }
  26346. if (lightIndex > 0) {
  26347. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26348. }
  26349. if (defines["SHADOW" + lightIndex]) {
  26350. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26351. }
  26352. if (defines["SHADOWPCF" + lightIndex]) {
  26353. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26354. }
  26355. if (defines["SHADOWESM" + lightIndex]) {
  26356. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  26357. }
  26358. }
  26359. };
  26360. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26361. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26362. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26363. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26364. var manager = mesh.morphTargetManager;
  26365. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26366. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26367. for (var index = 0; index < influencers; index++) {
  26368. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26369. if (normal) {
  26370. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26371. }
  26372. if (tangent) {
  26373. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26374. }
  26375. if (attribs.length > maxAttributesCount) {
  26376. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26377. }
  26378. }
  26379. }
  26380. };
  26381. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26382. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26383. fallbacks.addCPUSkinningFallback(0, mesh);
  26384. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26385. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26386. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26387. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26388. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26389. }
  26390. }
  26391. };
  26392. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26393. if (defines["INSTANCES"]) {
  26394. attribs.push("world0");
  26395. attribs.push("world1");
  26396. attribs.push("world2");
  26397. attribs.push("world3");
  26398. }
  26399. };
  26400. // Bindings
  26401. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26402. if (light.shadowEnabled && mesh.receiveShadows) {
  26403. var shadowGenerator = light.getShadowGenerator();
  26404. if (shadowGenerator) {
  26405. shadowGenerator.bindShadowLight(lightIndex, effect);
  26406. }
  26407. }
  26408. };
  26409. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26410. light.transferToEffect(effect, lightIndex + "");
  26411. };
  26412. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26413. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26414. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26415. var lightIndex = 0;
  26416. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26417. var light = _a[_i];
  26418. var scaledIntensity = light.getScaledIntensity();
  26419. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26420. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26421. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26422. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26423. if (defines["SPECULARTERM"]) {
  26424. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26425. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26426. }
  26427. // Shadows
  26428. if (scene.shadowsEnabled) {
  26429. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26430. }
  26431. light._uniformBuffer.update();
  26432. lightIndex++;
  26433. if (lightIndex === maxSimultaneousLights)
  26434. break;
  26435. }
  26436. };
  26437. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26438. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26439. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26440. effect.setColor3("vFogColor", scene.fogColor);
  26441. }
  26442. };
  26443. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26444. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26445. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26446. if (matrices && effect) {
  26447. effect.setMatrices("mBones", matrices);
  26448. }
  26449. }
  26450. };
  26451. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26452. var manager = abstractMesh.morphTargetManager;
  26453. if (!abstractMesh || !manager) {
  26454. return;
  26455. }
  26456. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26457. };
  26458. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26459. if (defines["LOGARITHMICDEPTH"]) {
  26460. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26461. }
  26462. };
  26463. MaterialHelper.BindClipPlane = function (effect, scene) {
  26464. if (scene.clipPlane) {
  26465. var clipPlane = scene.clipPlane;
  26466. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26467. }
  26468. };
  26469. return MaterialHelper;
  26470. }());
  26471. BABYLON.MaterialHelper = MaterialHelper;
  26472. })(BABYLON || (BABYLON = {}));
  26473. //# sourceMappingURL=babylon.materialHelper.js.map
  26474. var BABYLON;
  26475. (function (BABYLON) {
  26476. var MaterialDefines = /** @class */ (function () {
  26477. function MaterialDefines() {
  26478. this._isDirty = true;
  26479. this._areLightsDirty = true;
  26480. this._areAttributesDirty = true;
  26481. this._areTexturesDirty = true;
  26482. this._areFresnelDirty = true;
  26483. this._areMiscDirty = true;
  26484. this._areImageProcessingDirty = true;
  26485. this._normals = false;
  26486. this._uvs = false;
  26487. this._needNormals = false;
  26488. this._needUVs = false;
  26489. }
  26490. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26491. get: function () {
  26492. return this._isDirty;
  26493. },
  26494. enumerable: true,
  26495. configurable: true
  26496. });
  26497. MaterialDefines.prototype.markAsProcessed = function () {
  26498. this._isDirty = false;
  26499. this._areAttributesDirty = false;
  26500. this._areTexturesDirty = false;
  26501. this._areFresnelDirty = false;
  26502. this._areLightsDirty = false;
  26503. this._areMiscDirty = false;
  26504. this._areImageProcessingDirty = false;
  26505. };
  26506. MaterialDefines.prototype.markAsUnprocessed = function () {
  26507. this._isDirty = true;
  26508. };
  26509. MaterialDefines.prototype.markAllAsDirty = function () {
  26510. this._areTexturesDirty = true;
  26511. this._areAttributesDirty = true;
  26512. this._areLightsDirty = true;
  26513. this._areFresnelDirty = true;
  26514. this._areMiscDirty = true;
  26515. this._areImageProcessingDirty = true;
  26516. this._isDirty = true;
  26517. };
  26518. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26519. this._areImageProcessingDirty = true;
  26520. this._isDirty = true;
  26521. };
  26522. MaterialDefines.prototype.markAsLightDirty = function () {
  26523. this._areLightsDirty = true;
  26524. this._isDirty = true;
  26525. };
  26526. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26527. this._areAttributesDirty = true;
  26528. this._isDirty = true;
  26529. };
  26530. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26531. this._areTexturesDirty = true;
  26532. this._isDirty = true;
  26533. };
  26534. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26535. this._areFresnelDirty = true;
  26536. this._isDirty = true;
  26537. };
  26538. MaterialDefines.prototype.markAsMiscDirty = function () {
  26539. this._areMiscDirty = true;
  26540. this._isDirty = true;
  26541. };
  26542. MaterialDefines.prototype.rebuild = function () {
  26543. if (this._keys) {
  26544. delete this._keys;
  26545. }
  26546. this._keys = [];
  26547. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26548. var key = _a[_i];
  26549. if (key[0] === "_") {
  26550. continue;
  26551. }
  26552. this._keys.push(key);
  26553. }
  26554. };
  26555. MaterialDefines.prototype.isEqual = function (other) {
  26556. if (this._keys.length !== other._keys.length) {
  26557. return false;
  26558. }
  26559. for (var index = 0; index < this._keys.length; index++) {
  26560. var prop = this._keys[index];
  26561. if (this[prop] !== other[prop]) {
  26562. return false;
  26563. }
  26564. }
  26565. return true;
  26566. };
  26567. MaterialDefines.prototype.cloneTo = function (other) {
  26568. if (this._keys.length !== other._keys.length) {
  26569. other._keys = this._keys.slice(0);
  26570. }
  26571. for (var index = 0; index < this._keys.length; index++) {
  26572. var prop = this._keys[index];
  26573. other[prop] = this[prop];
  26574. }
  26575. };
  26576. MaterialDefines.prototype.reset = function () {
  26577. for (var index = 0; index < this._keys.length; index++) {
  26578. var prop = this._keys[index];
  26579. if (typeof (this[prop]) === "number") {
  26580. this[prop] = 0;
  26581. }
  26582. else {
  26583. this[prop] = false;
  26584. }
  26585. }
  26586. };
  26587. MaterialDefines.prototype.toString = function () {
  26588. var result = "";
  26589. for (var index = 0; index < this._keys.length; index++) {
  26590. var prop = this._keys[index];
  26591. var value = this[prop];
  26592. if (typeof (value) === "number") {
  26593. result += "#define " + prop + " " + this[prop] + "\n";
  26594. }
  26595. else if (value) {
  26596. result += "#define " + prop + "\n";
  26597. }
  26598. }
  26599. return result;
  26600. };
  26601. return MaterialDefines;
  26602. }());
  26603. BABYLON.MaterialDefines = MaterialDefines;
  26604. var Material = /** @class */ (function () {
  26605. function Material(name, scene, doNotAdd) {
  26606. this.checkReadyOnEveryCall = false;
  26607. this.checkReadyOnlyOnce = false;
  26608. this.state = "";
  26609. this.alpha = 1.0;
  26610. this._backFaceCulling = true;
  26611. this.doNotSerialize = false;
  26612. this.storeEffectOnSubMeshes = false;
  26613. /**
  26614. * An event triggered when the material is disposed.
  26615. * @type {BABYLON.Observable}
  26616. */
  26617. this.onDisposeObservable = new BABYLON.Observable();
  26618. /**
  26619. * An event triggered when the material is bound.
  26620. * @type {BABYLON.Observable}
  26621. */
  26622. this.onBindObservable = new BABYLON.Observable();
  26623. /**
  26624. * An event triggered when the material is unbound.
  26625. * @type {BABYLON.Observable}
  26626. */
  26627. this.onUnBindObservable = new BABYLON.Observable();
  26628. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26629. this._needDepthPrePass = false;
  26630. this.disableDepthWrite = false;
  26631. this.forceDepthWrite = false;
  26632. this.separateCullingPass = false;
  26633. this._fogEnabled = true;
  26634. this.pointSize = 1.0;
  26635. this.zOffset = 0;
  26636. this._wasPreviouslyReady = false;
  26637. this._fillMode = Material.TriangleFillMode;
  26638. this.name = name;
  26639. this.id = name || BABYLON.Tools.RandomId();
  26640. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26641. if (this._scene.useRightHandedSystem) {
  26642. this.sideOrientation = Material.ClockWiseSideOrientation;
  26643. }
  26644. else {
  26645. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26646. }
  26647. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26648. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26649. if (!doNotAdd) {
  26650. this._scene.materials.push(this);
  26651. }
  26652. }
  26653. Object.defineProperty(Material, "TriangleFillMode", {
  26654. get: function () {
  26655. return Material._TriangleFillMode;
  26656. },
  26657. enumerable: true,
  26658. configurable: true
  26659. });
  26660. Object.defineProperty(Material, "WireFrameFillMode", {
  26661. get: function () {
  26662. return Material._WireFrameFillMode;
  26663. },
  26664. enumerable: true,
  26665. configurable: true
  26666. });
  26667. Object.defineProperty(Material, "PointFillMode", {
  26668. get: function () {
  26669. return Material._PointFillMode;
  26670. },
  26671. enumerable: true,
  26672. configurable: true
  26673. });
  26674. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26675. get: function () {
  26676. return Material._ClockWiseSideOrientation;
  26677. },
  26678. enumerable: true,
  26679. configurable: true
  26680. });
  26681. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26682. get: function () {
  26683. return Material._CounterClockWiseSideOrientation;
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. Object.defineProperty(Material, "TextureDirtyFlag", {
  26689. get: function () {
  26690. return Material._TextureDirtyFlag;
  26691. },
  26692. enumerable: true,
  26693. configurable: true
  26694. });
  26695. Object.defineProperty(Material, "LightDirtyFlag", {
  26696. get: function () {
  26697. return Material._LightDirtyFlag;
  26698. },
  26699. enumerable: true,
  26700. configurable: true
  26701. });
  26702. Object.defineProperty(Material, "FresnelDirtyFlag", {
  26703. get: function () {
  26704. return Material._FresnelDirtyFlag;
  26705. },
  26706. enumerable: true,
  26707. configurable: true
  26708. });
  26709. Object.defineProperty(Material, "AttributesDirtyFlag", {
  26710. get: function () {
  26711. return Material._AttributesDirtyFlag;
  26712. },
  26713. enumerable: true,
  26714. configurable: true
  26715. });
  26716. Object.defineProperty(Material, "MiscDirtyFlag", {
  26717. get: function () {
  26718. return Material._MiscDirtyFlag;
  26719. },
  26720. enumerable: true,
  26721. configurable: true
  26722. });
  26723. Object.defineProperty(Material.prototype, "backFaceCulling", {
  26724. get: function () {
  26725. return this._backFaceCulling;
  26726. },
  26727. set: function (value) {
  26728. if (this._backFaceCulling === value) {
  26729. return;
  26730. }
  26731. this._backFaceCulling = value;
  26732. this.markAsDirty(Material.TextureDirtyFlag);
  26733. },
  26734. enumerable: true,
  26735. configurable: true
  26736. });
  26737. Object.defineProperty(Material.prototype, "onDispose", {
  26738. set: function (callback) {
  26739. if (this._onDisposeObserver) {
  26740. this.onDisposeObservable.remove(this._onDisposeObserver);
  26741. }
  26742. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26743. },
  26744. enumerable: true,
  26745. configurable: true
  26746. });
  26747. Object.defineProperty(Material.prototype, "onBind", {
  26748. set: function (callback) {
  26749. if (this._onBindObserver) {
  26750. this.onBindObservable.remove(this._onBindObserver);
  26751. }
  26752. this._onBindObserver = this.onBindObservable.add(callback);
  26753. },
  26754. enumerable: true,
  26755. configurable: true
  26756. });
  26757. Object.defineProperty(Material.prototype, "alphaMode", {
  26758. get: function () {
  26759. return this._alphaMode;
  26760. },
  26761. set: function (value) {
  26762. if (this._alphaMode === value) {
  26763. return;
  26764. }
  26765. this._alphaMode = value;
  26766. this.markAsDirty(Material.TextureDirtyFlag);
  26767. },
  26768. enumerable: true,
  26769. configurable: true
  26770. });
  26771. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  26772. get: function () {
  26773. return this._needDepthPrePass;
  26774. },
  26775. set: function (value) {
  26776. if (this._needDepthPrePass === value) {
  26777. return;
  26778. }
  26779. this._needDepthPrePass = value;
  26780. if (this._needDepthPrePass) {
  26781. this.checkReadyOnEveryCall = true;
  26782. }
  26783. },
  26784. enumerable: true,
  26785. configurable: true
  26786. });
  26787. Object.defineProperty(Material.prototype, "fogEnabled", {
  26788. get: function () {
  26789. return this._fogEnabled;
  26790. },
  26791. set: function (value) {
  26792. if (this._fogEnabled === value) {
  26793. return;
  26794. }
  26795. this._fogEnabled = value;
  26796. this.markAsDirty(Material.MiscDirtyFlag);
  26797. },
  26798. enumerable: true,
  26799. configurable: true
  26800. });
  26801. Object.defineProperty(Material.prototype, "wireframe", {
  26802. get: function () {
  26803. return this._fillMode === Material.WireFrameFillMode;
  26804. },
  26805. set: function (value) {
  26806. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26807. },
  26808. enumerable: true,
  26809. configurable: true
  26810. });
  26811. Object.defineProperty(Material.prototype, "pointsCloud", {
  26812. get: function () {
  26813. return this._fillMode === Material.PointFillMode;
  26814. },
  26815. set: function (value) {
  26816. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26817. },
  26818. enumerable: true,
  26819. configurable: true
  26820. });
  26821. Object.defineProperty(Material.prototype, "fillMode", {
  26822. get: function () {
  26823. return this._fillMode;
  26824. },
  26825. set: function (value) {
  26826. if (this._fillMode === value) {
  26827. return;
  26828. }
  26829. this._fillMode = value;
  26830. this.markAsDirty(Material.MiscDirtyFlag);
  26831. },
  26832. enumerable: true,
  26833. configurable: true
  26834. });
  26835. /**
  26836. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26837. * subclasses should override adding information pertainent to themselves
  26838. */
  26839. Material.prototype.toString = function (fullDetails) {
  26840. var ret = "Name: " + this.name;
  26841. if (fullDetails) {
  26842. }
  26843. return ret;
  26844. };
  26845. /**
  26846. * Child classes can use it to update shaders
  26847. */
  26848. Material.prototype.getClassName = function () {
  26849. return "Material";
  26850. };
  26851. Object.defineProperty(Material.prototype, "isFrozen", {
  26852. get: function () {
  26853. return this.checkReadyOnlyOnce;
  26854. },
  26855. enumerable: true,
  26856. configurable: true
  26857. });
  26858. Material.prototype.freeze = function () {
  26859. this.checkReadyOnlyOnce = true;
  26860. };
  26861. Material.prototype.unfreeze = function () {
  26862. this.checkReadyOnlyOnce = false;
  26863. };
  26864. Material.prototype.isReady = function (mesh, useInstances) {
  26865. return true;
  26866. };
  26867. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  26868. return false;
  26869. };
  26870. Material.prototype.getEffect = function () {
  26871. return this._effect;
  26872. };
  26873. Material.prototype.getScene = function () {
  26874. return this._scene;
  26875. };
  26876. Material.prototype.needAlphaBlending = function () {
  26877. return (this.alpha < 1.0);
  26878. };
  26879. Material.prototype.needAlphaTesting = function () {
  26880. return false;
  26881. };
  26882. Material.prototype.getAlphaTestTexture = function () {
  26883. return null;
  26884. };
  26885. Material.prototype.markDirty = function () {
  26886. this._wasPreviouslyReady = false;
  26887. };
  26888. Material.prototype._preBind = function (effect, overrideOrientation) {
  26889. if (overrideOrientation === void 0) { overrideOrientation = null; }
  26890. var engine = this._scene.getEngine();
  26891. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  26892. var reverse = orientation === Material.ClockWiseSideOrientation;
  26893. engine.enableEffect(effect ? effect : this._effect);
  26894. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26895. return reverse;
  26896. };
  26897. Material.prototype.bind = function (world, mesh) {
  26898. };
  26899. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  26900. };
  26901. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26902. };
  26903. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  26904. sceneUbo.bindToEffect(effect, "Scene");
  26905. };
  26906. Material.prototype.bindView = function (effect) {
  26907. if (!this._useUBO) {
  26908. effect.setMatrix("view", this.getScene().getViewMatrix());
  26909. }
  26910. else {
  26911. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26912. }
  26913. };
  26914. Material.prototype.bindViewProjection = function (effect) {
  26915. if (!this._useUBO) {
  26916. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26917. }
  26918. else {
  26919. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26920. }
  26921. };
  26922. Material.prototype._afterBind = function (mesh) {
  26923. this._scene._cachedMaterial = this;
  26924. if (mesh) {
  26925. this._scene._cachedVisibility = mesh.visibility;
  26926. }
  26927. else {
  26928. this._scene._cachedVisibility = 1;
  26929. }
  26930. if (mesh) {
  26931. this.onBindObservable.notifyObservers(mesh);
  26932. }
  26933. if (this.disableDepthWrite) {
  26934. var engine = this._scene.getEngine();
  26935. this._cachedDepthWriteState = engine.getDepthWrite();
  26936. engine.setDepthWrite(false);
  26937. }
  26938. };
  26939. Material.prototype.unbind = function () {
  26940. this.onUnBindObservable.notifyObservers(this);
  26941. if (this.disableDepthWrite) {
  26942. var engine = this._scene.getEngine();
  26943. engine.setDepthWrite(this._cachedDepthWriteState);
  26944. }
  26945. };
  26946. Material.prototype.getActiveTextures = function () {
  26947. return [];
  26948. };
  26949. Material.prototype.hasTexture = function (texture) {
  26950. return false;
  26951. };
  26952. Material.prototype.clone = function (name) {
  26953. return null;
  26954. };
  26955. Material.prototype.getBindedMeshes = function () {
  26956. var result = new Array();
  26957. for (var index = 0; index < this._scene.meshes.length; index++) {
  26958. var mesh = this._scene.meshes[index];
  26959. if (mesh.material === this) {
  26960. result.push(mesh);
  26961. }
  26962. }
  26963. return result;
  26964. };
  26965. /**
  26966. * Force shader compilation including textures ready check
  26967. */
  26968. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  26969. var _this = this;
  26970. var subMesh = new BABYLON.BaseSubMesh();
  26971. var scene = this.getScene();
  26972. var engine = scene.getEngine();
  26973. var checkReady = function () {
  26974. if (!_this._scene || !_this._scene.getEngine()) {
  26975. return;
  26976. }
  26977. if (subMesh._materialDefines) {
  26978. subMesh._materialDefines._renderId = -1;
  26979. }
  26980. var alphaTestState = engine.getAlphaTesting();
  26981. var clipPlaneState = scene.clipPlane;
  26982. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  26983. if (options && options.clipPlane) {
  26984. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  26985. }
  26986. if (_this.storeEffectOnSubMeshes) {
  26987. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  26988. if (onCompiled) {
  26989. onCompiled(_this);
  26990. }
  26991. }
  26992. else {
  26993. setTimeout(checkReady, 16);
  26994. }
  26995. }
  26996. else {
  26997. if (_this.isReady(mesh)) {
  26998. if (onCompiled) {
  26999. onCompiled(_this);
  27000. }
  27001. }
  27002. else {
  27003. setTimeout(checkReady, 16);
  27004. }
  27005. }
  27006. engine.setAlphaTesting(alphaTestState);
  27007. if (options && options.clipPlane) {
  27008. scene.clipPlane = clipPlaneState;
  27009. }
  27010. };
  27011. checkReady();
  27012. };
  27013. Material.prototype.markAsDirty = function (flag) {
  27014. if (flag & Material.TextureDirtyFlag) {
  27015. this._markAllSubMeshesAsTexturesDirty();
  27016. }
  27017. if (flag & Material.LightDirtyFlag) {
  27018. this._markAllSubMeshesAsLightsDirty();
  27019. }
  27020. if (flag & Material.FresnelDirtyFlag) {
  27021. this._markAllSubMeshesAsFresnelDirty();
  27022. }
  27023. if (flag & Material.AttributesDirtyFlag) {
  27024. this._markAllSubMeshesAsAttributesDirty();
  27025. }
  27026. if (flag & Material.MiscDirtyFlag) {
  27027. this._markAllSubMeshesAsMiscDirty();
  27028. }
  27029. this.getScene().resetCachedMaterial();
  27030. };
  27031. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27032. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27033. var mesh = _a[_i];
  27034. if (!mesh.subMeshes) {
  27035. continue;
  27036. }
  27037. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27038. var subMesh = _c[_b];
  27039. if (subMesh.getMaterial() !== this) {
  27040. continue;
  27041. }
  27042. if (!subMesh._materialDefines) {
  27043. continue;
  27044. }
  27045. func(subMesh._materialDefines);
  27046. }
  27047. }
  27048. };
  27049. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27050. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27051. };
  27052. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27053. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27054. };
  27055. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27056. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27057. };
  27058. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27059. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27060. };
  27061. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27062. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27063. };
  27064. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27065. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27066. };
  27067. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27068. // Animations
  27069. this.getScene().stopAnimation(this);
  27070. // Remove from scene
  27071. var index = this._scene.materials.indexOf(this);
  27072. if (index >= 0) {
  27073. this._scene.materials.splice(index, 1);
  27074. }
  27075. // Remove from meshes
  27076. for (index = 0; index < this._scene.meshes.length; index++) {
  27077. var mesh = this._scene.meshes[index];
  27078. if (mesh.material === this) {
  27079. mesh.material = null;
  27080. if (mesh.geometry) {
  27081. var geometry = (mesh.geometry);
  27082. if (this.storeEffectOnSubMeshes) {
  27083. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27084. var subMesh = _a[_i];
  27085. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27086. if (forceDisposeEffect && subMesh._materialEffect) {
  27087. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27088. }
  27089. }
  27090. }
  27091. else {
  27092. geometry._releaseVertexArrayObject(this._effect);
  27093. }
  27094. }
  27095. }
  27096. }
  27097. this._uniformBuffer.dispose();
  27098. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27099. if (forceDisposeEffect && this._effect) {
  27100. if (!this.storeEffectOnSubMeshes) {
  27101. this._scene.getEngine()._releaseEffect(this._effect);
  27102. }
  27103. this._effect = null;
  27104. }
  27105. // Callback
  27106. this.onDisposeObservable.notifyObservers(this);
  27107. this.onDisposeObservable.clear();
  27108. this.onBindObservable.clear();
  27109. this.onUnBindObservable.clear();
  27110. };
  27111. Material.prototype.serialize = function () {
  27112. return BABYLON.SerializationHelper.Serialize(this);
  27113. };
  27114. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27115. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27116. multiMaterial.id = parsedMultiMaterial.id;
  27117. if (BABYLON.Tags) {
  27118. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27119. }
  27120. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27121. var subMatId = parsedMultiMaterial.materials[matIndex];
  27122. if (subMatId) {
  27123. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27124. }
  27125. else {
  27126. multiMaterial.subMaterials.push(null);
  27127. }
  27128. }
  27129. return multiMaterial;
  27130. };
  27131. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27132. if (!parsedMaterial.customType) {
  27133. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27134. }
  27135. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27136. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27137. if (!BABYLON.LegacyPBRMaterial) {
  27138. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27139. return;
  27140. }
  27141. }
  27142. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27143. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27144. ;
  27145. };
  27146. Material._TriangleFillMode = 0;
  27147. Material._WireFrameFillMode = 1;
  27148. Material._PointFillMode = 2;
  27149. Material._ClockWiseSideOrientation = 0;
  27150. Material._CounterClockWiseSideOrientation = 1;
  27151. Material._TextureDirtyFlag = 1;
  27152. Material._LightDirtyFlag = 2;
  27153. Material._FresnelDirtyFlag = 4;
  27154. Material._AttributesDirtyFlag = 8;
  27155. Material._MiscDirtyFlag = 16;
  27156. __decorate([
  27157. BABYLON.serialize()
  27158. ], Material.prototype, "id", void 0);
  27159. __decorate([
  27160. BABYLON.serialize()
  27161. ], Material.prototype, "name", void 0);
  27162. __decorate([
  27163. BABYLON.serialize()
  27164. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27165. __decorate([
  27166. BABYLON.serialize()
  27167. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27168. __decorate([
  27169. BABYLON.serialize()
  27170. ], Material.prototype, "state", void 0);
  27171. __decorate([
  27172. BABYLON.serialize()
  27173. ], Material.prototype, "alpha", void 0);
  27174. __decorate([
  27175. BABYLON.serialize("backFaceCulling")
  27176. ], Material.prototype, "_backFaceCulling", void 0);
  27177. __decorate([
  27178. BABYLON.serialize()
  27179. ], Material.prototype, "sideOrientation", void 0);
  27180. __decorate([
  27181. BABYLON.serialize("alphaMode")
  27182. ], Material.prototype, "_alphaMode", void 0);
  27183. __decorate([
  27184. BABYLON.serialize()
  27185. ], Material.prototype, "_needDepthPrePass", void 0);
  27186. __decorate([
  27187. BABYLON.serialize()
  27188. ], Material.prototype, "disableDepthWrite", void 0);
  27189. __decorate([
  27190. BABYLON.serialize()
  27191. ], Material.prototype, "forceDepthWrite", void 0);
  27192. __decorate([
  27193. BABYLON.serialize()
  27194. ], Material.prototype, "separateCullingPass", void 0);
  27195. __decorate([
  27196. BABYLON.serialize("fogEnabled")
  27197. ], Material.prototype, "_fogEnabled", void 0);
  27198. __decorate([
  27199. BABYLON.serialize()
  27200. ], Material.prototype, "pointSize", void 0);
  27201. __decorate([
  27202. BABYLON.serialize()
  27203. ], Material.prototype, "zOffset", void 0);
  27204. __decorate([
  27205. BABYLON.serialize()
  27206. ], Material.prototype, "wireframe", null);
  27207. __decorate([
  27208. BABYLON.serialize()
  27209. ], Material.prototype, "pointsCloud", null);
  27210. __decorate([
  27211. BABYLON.serialize()
  27212. ], Material.prototype, "fillMode", null);
  27213. return Material;
  27214. }());
  27215. BABYLON.Material = Material;
  27216. })(BABYLON || (BABYLON = {}));
  27217. //# sourceMappingURL=babylon.material.js.map
  27218. var BABYLON;
  27219. (function (BABYLON) {
  27220. var UniformBuffer = /** @class */ (function () {
  27221. /**
  27222. * Uniform buffer objects.
  27223. *
  27224. * Handles blocks of uniform on the GPU.
  27225. *
  27226. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27227. *
  27228. * For more information, please refer to :
  27229. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27230. */
  27231. function UniformBuffer(engine, data, dynamic) {
  27232. this._engine = engine;
  27233. this._noUBO = !engine.supportsUniformBuffers;
  27234. this._dynamic = dynamic;
  27235. this._data = data || [];
  27236. this._uniformLocations = {};
  27237. this._uniformSizes = {};
  27238. this._uniformLocationPointer = 0;
  27239. this._needSync = false;
  27240. if (this._noUBO) {
  27241. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27242. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27243. this.updateFloat = this._updateFloatForEffect;
  27244. this.updateFloat2 = this._updateFloat2ForEffect;
  27245. this.updateFloat3 = this._updateFloat3ForEffect;
  27246. this.updateFloat4 = this._updateFloat4ForEffect;
  27247. this.updateMatrix = this._updateMatrixForEffect;
  27248. this.updateVector3 = this._updateVector3ForEffect;
  27249. this.updateVector4 = this._updateVector4ForEffect;
  27250. this.updateColor3 = this._updateColor3ForEffect;
  27251. this.updateColor4 = this._updateColor4ForEffect;
  27252. }
  27253. else {
  27254. this._engine._uniformBuffers.push(this);
  27255. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27256. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27257. this.updateFloat = this._updateFloatForUniform;
  27258. this.updateFloat2 = this._updateFloat2ForUniform;
  27259. this.updateFloat3 = this._updateFloat3ForUniform;
  27260. this.updateFloat4 = this._updateFloat4ForUniform;
  27261. this.updateMatrix = this._updateMatrixForUniform;
  27262. this.updateVector3 = this._updateVector3ForUniform;
  27263. this.updateVector4 = this._updateVector4ForUniform;
  27264. this.updateColor3 = this._updateColor3ForUniform;
  27265. this.updateColor4 = this._updateColor4ForUniform;
  27266. }
  27267. }
  27268. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27269. // Properties
  27270. /**
  27271. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27272. * or just falling back on setUniformXXX calls.
  27273. */
  27274. get: function () {
  27275. return !this._noUBO;
  27276. },
  27277. enumerable: true,
  27278. configurable: true
  27279. });
  27280. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27281. /**
  27282. * Indicates if the WebGL underlying uniform buffer is in sync
  27283. * with the javascript cache data.
  27284. */
  27285. get: function () {
  27286. return !this._needSync;
  27287. },
  27288. enumerable: true,
  27289. configurable: true
  27290. });
  27291. /**
  27292. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27293. * Also, a dynamic UniformBuffer will disable cache verification and always
  27294. * update the underlying WebGL uniform buffer to the GPU.
  27295. */
  27296. UniformBuffer.prototype.isDynamic = function () {
  27297. return this._dynamic !== undefined;
  27298. };
  27299. /**
  27300. * The data cache on JS side.
  27301. */
  27302. UniformBuffer.prototype.getData = function () {
  27303. return this._bufferData;
  27304. };
  27305. /**
  27306. * The underlying WebGL Uniform buffer.
  27307. */
  27308. UniformBuffer.prototype.getBuffer = function () {
  27309. return this._buffer;
  27310. };
  27311. /**
  27312. * std140 layout specifies how to align data within an UBO structure.
  27313. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27314. * for specs.
  27315. */
  27316. UniformBuffer.prototype._fillAlignment = function (size) {
  27317. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27318. // and 4x4 matrices
  27319. // TODO : change if other types are used
  27320. var alignment;
  27321. if (size <= 2) {
  27322. alignment = size;
  27323. }
  27324. else {
  27325. alignment = 4;
  27326. }
  27327. if ((this._uniformLocationPointer % alignment) !== 0) {
  27328. var oldPointer = this._uniformLocationPointer;
  27329. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27330. var diff = this._uniformLocationPointer - oldPointer;
  27331. for (var i = 0; i < diff; i++) {
  27332. this._data.push(0);
  27333. }
  27334. }
  27335. };
  27336. /**
  27337. * Adds an uniform in the buffer.
  27338. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27339. * for the layout to be correct !
  27340. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27341. * @param {number|number[]} size Data size, or data directly.
  27342. */
  27343. UniformBuffer.prototype.addUniform = function (name, size) {
  27344. if (this._noUBO) {
  27345. return;
  27346. }
  27347. if (this._uniformLocations[name] !== undefined) {
  27348. // Already existing uniform
  27349. return;
  27350. }
  27351. // This function must be called in the order of the shader layout !
  27352. // size can be the size of the uniform, or data directly
  27353. var data;
  27354. if (size instanceof Array) {
  27355. data = size;
  27356. size = data.length;
  27357. }
  27358. else {
  27359. size = size;
  27360. data = [];
  27361. // Fill with zeros
  27362. for (var i = 0; i < size; i++) {
  27363. data.push(0);
  27364. }
  27365. }
  27366. this._fillAlignment(size);
  27367. this._uniformSizes[name] = size;
  27368. this._uniformLocations[name] = this._uniformLocationPointer;
  27369. this._uniformLocationPointer += size;
  27370. for (var i = 0; i < size; i++) {
  27371. this._data.push(data[i]);
  27372. }
  27373. this._needSync = true;
  27374. };
  27375. /**
  27376. * Wrapper for addUniform.
  27377. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27378. * @param {Matrix} mat A 4x4 matrix.
  27379. */
  27380. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27381. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27382. };
  27383. /**
  27384. * Wrapper for addUniform.
  27385. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27386. * @param {number} x
  27387. * @param {number} y
  27388. */
  27389. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27390. var temp = [x, y];
  27391. this.addUniform(name, temp);
  27392. };
  27393. /**
  27394. * Wrapper for addUniform.
  27395. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27396. * @param {number} x
  27397. * @param {number} y
  27398. * @param {number} z
  27399. */
  27400. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27401. var temp = [x, y, z];
  27402. this.addUniform(name, temp);
  27403. };
  27404. /**
  27405. * Wrapper for addUniform.
  27406. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27407. * @param {Color3} color
  27408. */
  27409. UniformBuffer.prototype.addColor3 = function (name, color) {
  27410. var temp = new Array();
  27411. color.toArray(temp);
  27412. this.addUniform(name, temp);
  27413. };
  27414. /**
  27415. * Wrapper for addUniform.
  27416. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27417. * @param {Color3} color
  27418. * @param {number} alpha
  27419. */
  27420. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27421. var temp = new Array();
  27422. color.toArray(temp);
  27423. temp.push(alpha);
  27424. this.addUniform(name, temp);
  27425. };
  27426. /**
  27427. * Wrapper for addUniform.
  27428. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27429. * @param {Vector3} vector
  27430. */
  27431. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27432. var temp = new Array();
  27433. vector.toArray(temp);
  27434. this.addUniform(name, temp);
  27435. };
  27436. /**
  27437. * Wrapper for addUniform.
  27438. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27439. */
  27440. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27441. this.addUniform(name, 12);
  27442. };
  27443. /**
  27444. * Wrapper for addUniform.
  27445. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27446. */
  27447. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27448. this.addUniform(name, 8);
  27449. };
  27450. /**
  27451. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27452. */
  27453. UniformBuffer.prototype.create = function () {
  27454. if (this._noUBO) {
  27455. return;
  27456. }
  27457. if (this._buffer) {
  27458. return; // nothing to do
  27459. }
  27460. // See spec, alignment must be filled as a vec4
  27461. this._fillAlignment(4);
  27462. this._bufferData = new Float32Array(this._data);
  27463. this._rebuild();
  27464. this._needSync = true;
  27465. };
  27466. UniformBuffer.prototype._rebuild = function () {
  27467. if (this._noUBO) {
  27468. return;
  27469. }
  27470. if (this._dynamic) {
  27471. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27472. }
  27473. else {
  27474. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27475. }
  27476. };
  27477. /**
  27478. * Updates the WebGL Uniform Buffer on the GPU.
  27479. * If the `dynamic` flag is set to true, no cache comparison is done.
  27480. * Otherwise, the buffer will be updated only if the cache differs.
  27481. */
  27482. UniformBuffer.prototype.update = function () {
  27483. if (!this._buffer) {
  27484. this.create();
  27485. return;
  27486. }
  27487. if (!this._dynamic && !this._needSync) {
  27488. return;
  27489. }
  27490. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27491. this._needSync = false;
  27492. };
  27493. /**
  27494. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27495. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27496. * @param {number[]|Float32Array} data Flattened data
  27497. * @param {number} size Size of the data.
  27498. */
  27499. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27500. var location = this._uniformLocations[uniformName];
  27501. if (location === undefined) {
  27502. if (this._buffer) {
  27503. // Cannot add an uniform if the buffer is already created
  27504. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27505. return;
  27506. }
  27507. this.addUniform(uniformName, size);
  27508. location = this._uniformLocations[uniformName];
  27509. }
  27510. if (!this._buffer) {
  27511. this.create();
  27512. }
  27513. if (!this._dynamic) {
  27514. // Cache for static uniform buffers
  27515. var changed = false;
  27516. for (var i = 0; i < size; i++) {
  27517. if (this._bufferData[location + i] !== data[i]) {
  27518. changed = true;
  27519. this._bufferData[location + i] = data[i];
  27520. }
  27521. }
  27522. this._needSync = this._needSync || changed;
  27523. }
  27524. else {
  27525. // No cache for dynamic
  27526. for (var i = 0; i < size; i++) {
  27527. this._bufferData[location + i] = data[i];
  27528. }
  27529. }
  27530. };
  27531. // Update methods
  27532. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27533. // To match std140, matrix must be realigned
  27534. for (var i = 0; i < 3; i++) {
  27535. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27536. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27537. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27538. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27539. }
  27540. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27541. };
  27542. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27543. this._currentEffect.setMatrix3x3(name, matrix);
  27544. };
  27545. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27546. this._currentEffect.setMatrix2x2(name, matrix);
  27547. };
  27548. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27549. // To match std140, matrix must be realigned
  27550. for (var i = 0; i < 2; i++) {
  27551. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27552. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27553. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27554. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27555. }
  27556. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27557. };
  27558. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27559. this._currentEffect.setFloat(name, x);
  27560. };
  27561. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27562. UniformBuffer._tempBuffer[0] = x;
  27563. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27564. };
  27565. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27566. if (suffix === void 0) { suffix = ""; }
  27567. this._currentEffect.setFloat2(name + suffix, x, y);
  27568. };
  27569. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27570. if (suffix === void 0) { suffix = ""; }
  27571. UniformBuffer._tempBuffer[0] = x;
  27572. UniformBuffer._tempBuffer[1] = y;
  27573. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27574. };
  27575. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27576. if (suffix === void 0) { suffix = ""; }
  27577. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27578. };
  27579. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27580. if (suffix === void 0) { suffix = ""; }
  27581. UniformBuffer._tempBuffer[0] = x;
  27582. UniformBuffer._tempBuffer[1] = y;
  27583. UniformBuffer._tempBuffer[2] = z;
  27584. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27585. };
  27586. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27587. if (suffix === void 0) { suffix = ""; }
  27588. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27589. };
  27590. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27591. if (suffix === void 0) { suffix = ""; }
  27592. UniformBuffer._tempBuffer[0] = x;
  27593. UniformBuffer._tempBuffer[1] = y;
  27594. UniformBuffer._tempBuffer[2] = z;
  27595. UniformBuffer._tempBuffer[3] = w;
  27596. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27597. };
  27598. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27599. this._currentEffect.setMatrix(name, mat);
  27600. };
  27601. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27602. this.updateUniform(name, mat.toArray(), 16);
  27603. };
  27604. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27605. this._currentEffect.setVector3(name, vector);
  27606. };
  27607. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27608. vector.toArray(UniformBuffer._tempBuffer);
  27609. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27610. };
  27611. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27612. this._currentEffect.setVector4(name, vector);
  27613. };
  27614. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27615. vector.toArray(UniformBuffer._tempBuffer);
  27616. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27617. };
  27618. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27619. if (suffix === void 0) { suffix = ""; }
  27620. this._currentEffect.setColor3(name + suffix, color);
  27621. };
  27622. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27623. if (suffix === void 0) { suffix = ""; }
  27624. color.toArray(UniformBuffer._tempBuffer);
  27625. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27626. };
  27627. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27628. if (suffix === void 0) { suffix = ""; }
  27629. this._currentEffect.setColor4(name + suffix, color, alpha);
  27630. };
  27631. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27632. if (suffix === void 0) { suffix = ""; }
  27633. color.toArray(UniformBuffer._tempBuffer);
  27634. UniformBuffer._tempBuffer[3] = alpha;
  27635. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27636. };
  27637. /**
  27638. * Sets a sampler uniform on the effect.
  27639. * @param {string} name Name of the sampler.
  27640. * @param {Texture} texture
  27641. */
  27642. UniformBuffer.prototype.setTexture = function (name, texture) {
  27643. this._currentEffect.setTexture(name, texture);
  27644. };
  27645. /**
  27646. * Directly updates the value of the uniform in the cache AND on the GPU.
  27647. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27648. * @param {number[]|Float32Array} data Flattened data
  27649. */
  27650. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27651. this.updateUniform(uniformName, data, data.length);
  27652. this.update();
  27653. };
  27654. /**
  27655. * Binds this uniform buffer to an effect.
  27656. * @param {Effect} effect
  27657. * @param {string} name Name of the uniform block in the shader.
  27658. */
  27659. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27660. this._currentEffect = effect;
  27661. if (this._noUBO || !this._buffer) {
  27662. return;
  27663. }
  27664. effect.bindUniformBuffer(this._buffer, name);
  27665. };
  27666. /**
  27667. * Disposes the uniform buffer.
  27668. */
  27669. UniformBuffer.prototype.dispose = function () {
  27670. if (this._noUBO) {
  27671. return;
  27672. }
  27673. var index = this._engine._uniformBuffers.indexOf(this);
  27674. if (index !== -1) {
  27675. this._engine._uniformBuffers.splice(index, 1);
  27676. }
  27677. if (!this._buffer) {
  27678. return;
  27679. }
  27680. if (this._engine._releaseBuffer(this._buffer)) {
  27681. this._buffer = null;
  27682. }
  27683. };
  27684. // Pool for avoiding memory leaks
  27685. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  27686. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  27687. return UniformBuffer;
  27688. }());
  27689. BABYLON.UniformBuffer = UniformBuffer;
  27690. })(BABYLON || (BABYLON = {}));
  27691. //# sourceMappingURL=babylon.uniformBuffer.js.map
  27692. var BABYLON;
  27693. (function (BABYLON) {
  27694. var PushMaterial = /** @class */ (function (_super) {
  27695. __extends(PushMaterial, _super);
  27696. function PushMaterial(name, scene) {
  27697. var _this = _super.call(this, name, scene) || this;
  27698. _this.storeEffectOnSubMeshes = true;
  27699. return _this;
  27700. }
  27701. PushMaterial.prototype.getEffect = function () {
  27702. return this._activeEffect;
  27703. };
  27704. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  27705. if (!mesh) {
  27706. return false;
  27707. }
  27708. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27709. return true;
  27710. }
  27711. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  27712. };
  27713. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27714. this._activeEffect.setMatrix("world", world);
  27715. };
  27716. PushMaterial.prototype.bind = function (world, mesh) {
  27717. if (!mesh) {
  27718. return;
  27719. }
  27720. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  27721. };
  27722. PushMaterial.prototype._afterBind = function (mesh, effect) {
  27723. if (effect === void 0) { effect = null; }
  27724. _super.prototype._afterBind.call(this, mesh);
  27725. this.getScene()._cachedEffect = effect;
  27726. };
  27727. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  27728. if (visibility === void 0) { visibility = 1; }
  27729. return scene.isCachedMaterialInvalid(this, effect, visibility);
  27730. };
  27731. return PushMaterial;
  27732. }(BABYLON.Material));
  27733. BABYLON.PushMaterial = PushMaterial;
  27734. })(BABYLON || (BABYLON = {}));
  27735. //# sourceMappingURL=babylon.pushMaterial.js.map
  27736. var BABYLON;
  27737. (function (BABYLON) {
  27738. var VertexData = /** @class */ (function () {
  27739. function VertexData() {
  27740. }
  27741. VertexData.prototype.set = function (data, kind) {
  27742. switch (kind) {
  27743. case BABYLON.VertexBuffer.PositionKind:
  27744. this.positions = data;
  27745. break;
  27746. case BABYLON.VertexBuffer.NormalKind:
  27747. this.normals = data;
  27748. break;
  27749. case BABYLON.VertexBuffer.TangentKind:
  27750. this.tangents = data;
  27751. break;
  27752. case BABYLON.VertexBuffer.UVKind:
  27753. this.uvs = data;
  27754. break;
  27755. case BABYLON.VertexBuffer.UV2Kind:
  27756. this.uvs2 = data;
  27757. break;
  27758. case BABYLON.VertexBuffer.UV3Kind:
  27759. this.uvs3 = data;
  27760. break;
  27761. case BABYLON.VertexBuffer.UV4Kind:
  27762. this.uvs4 = data;
  27763. break;
  27764. case BABYLON.VertexBuffer.UV5Kind:
  27765. this.uvs5 = data;
  27766. break;
  27767. case BABYLON.VertexBuffer.UV6Kind:
  27768. this.uvs6 = data;
  27769. break;
  27770. case BABYLON.VertexBuffer.ColorKind:
  27771. this.colors = data;
  27772. break;
  27773. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27774. this.matricesIndices = data;
  27775. break;
  27776. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27777. this.matricesWeights = data;
  27778. break;
  27779. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27780. this.matricesIndicesExtra = data;
  27781. break;
  27782. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27783. this.matricesWeightsExtra = data;
  27784. break;
  27785. }
  27786. };
  27787. /**
  27788. * Associates the vertexData to the passed Mesh.
  27789. * Sets it as updatable or not (default `false`).
  27790. * Returns the VertexData.
  27791. */
  27792. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27793. this._applyTo(mesh, updatable);
  27794. return this;
  27795. };
  27796. /**
  27797. * Associates the vertexData to the passed Geometry.
  27798. * Sets it as updatable or not (default `false`).
  27799. * Returns the VertexData.
  27800. */
  27801. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27802. this._applyTo(geometry, updatable);
  27803. return this;
  27804. };
  27805. /**
  27806. * Updates the associated mesh.
  27807. * Returns the VertexData.
  27808. */
  27809. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27810. this._update(mesh);
  27811. return this;
  27812. };
  27813. /**
  27814. * Updates the associated geometry.
  27815. * Returns the VertexData.
  27816. */
  27817. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27818. this._update(geometry);
  27819. return this;
  27820. };
  27821. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27822. if (updatable === void 0) { updatable = false; }
  27823. if (this.positions) {
  27824. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27825. }
  27826. if (this.normals) {
  27827. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27828. }
  27829. if (this.tangents) {
  27830. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  27831. }
  27832. if (this.uvs) {
  27833. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27834. }
  27835. if (this.uvs2) {
  27836. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27837. }
  27838. if (this.uvs3) {
  27839. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27840. }
  27841. if (this.uvs4) {
  27842. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27843. }
  27844. if (this.uvs5) {
  27845. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27846. }
  27847. if (this.uvs6) {
  27848. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27849. }
  27850. if (this.colors) {
  27851. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27852. }
  27853. if (this.matricesIndices) {
  27854. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27855. }
  27856. if (this.matricesWeights) {
  27857. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27858. }
  27859. if (this.matricesIndicesExtra) {
  27860. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27861. }
  27862. if (this.matricesWeightsExtra) {
  27863. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27864. }
  27865. if (this.indices) {
  27866. meshOrGeometry.setIndices(this.indices, null, updatable);
  27867. }
  27868. return this;
  27869. };
  27870. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27871. if (this.positions) {
  27872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27873. }
  27874. if (this.normals) {
  27875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27876. }
  27877. if (this.tangents) {
  27878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  27879. }
  27880. if (this.uvs) {
  27881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27882. }
  27883. if (this.uvs2) {
  27884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27885. }
  27886. if (this.uvs3) {
  27887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27888. }
  27889. if (this.uvs4) {
  27890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27891. }
  27892. if (this.uvs5) {
  27893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27894. }
  27895. if (this.uvs6) {
  27896. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27897. }
  27898. if (this.colors) {
  27899. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27900. }
  27901. if (this.matricesIndices) {
  27902. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27903. }
  27904. if (this.matricesWeights) {
  27905. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27906. }
  27907. if (this.matricesIndicesExtra) {
  27908. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27909. }
  27910. if (this.matricesWeightsExtra) {
  27911. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27912. }
  27913. if (this.indices) {
  27914. meshOrGeometry.setIndices(this.indices, null);
  27915. }
  27916. return this;
  27917. };
  27918. /**
  27919. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  27920. * Returns the VertexData.
  27921. */
  27922. VertexData.prototype.transform = function (matrix) {
  27923. var transformed = BABYLON.Vector3.Zero();
  27924. var index;
  27925. if (this.positions) {
  27926. var position = BABYLON.Vector3.Zero();
  27927. for (index = 0; index < this.positions.length; index += 3) {
  27928. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27929. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27930. this.positions[index] = transformed.x;
  27931. this.positions[index + 1] = transformed.y;
  27932. this.positions[index + 2] = transformed.z;
  27933. }
  27934. }
  27935. if (this.normals) {
  27936. var normal = BABYLON.Vector3.Zero();
  27937. for (index = 0; index < this.normals.length; index += 3) {
  27938. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27939. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27940. this.normals[index] = transformed.x;
  27941. this.normals[index + 1] = transformed.y;
  27942. this.normals[index + 2] = transformed.z;
  27943. }
  27944. }
  27945. if (this.tangents) {
  27946. var tangent = BABYLON.Vector4.Zero();
  27947. var tangentTransformed = BABYLON.Vector4.Zero();
  27948. for (index = 0; index < this.tangents.length; index += 4) {
  27949. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  27950. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  27951. this.tangents[index] = tangentTransformed.x;
  27952. this.tangents[index + 1] = tangentTransformed.y;
  27953. this.tangents[index + 2] = tangentTransformed.z;
  27954. this.tangents[index + 3] = tangentTransformed.w;
  27955. }
  27956. }
  27957. return this;
  27958. };
  27959. /**
  27960. * Merges the passed VertexData into the current one.
  27961. * Returns the modified VertexData.
  27962. */
  27963. VertexData.prototype.merge = function (other, options) {
  27964. options = options || {};
  27965. if (other.indices) {
  27966. if (!this.indices) {
  27967. this.indices = [];
  27968. }
  27969. var offset = this.positions ? this.positions.length / 3 : 0;
  27970. for (var index = 0; index < other.indices.length; index++) {
  27971. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  27972. this.indices.push(other.indices[index] + offset);
  27973. }
  27974. }
  27975. this.positions = this._mergeElement(this.positions, other.positions);
  27976. if (!this.positions) {
  27977. return this;
  27978. }
  27979. var count = this.positions.length / 3;
  27980. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  27981. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  27982. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  27983. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  27984. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  27985. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  27986. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  27987. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  27988. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  27989. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  27990. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  27991. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  27992. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  27993. return this;
  27994. };
  27995. VertexData.prototype._mergeElement = function (source, other, length) {
  27996. if (length === void 0) { length = 0; }
  27997. if (!other && !source) {
  27998. return null;
  27999. }
  28000. if (!other) {
  28001. return this._mergeElement(source, new Float32Array(source.length), length);
  28002. }
  28003. if (!source) {
  28004. if (length === 0 || length === other.length) {
  28005. return other;
  28006. }
  28007. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28008. }
  28009. var len = other.length + source.length;
  28010. var isSrcTypedArray = source instanceof Float32Array;
  28011. var isOthTypedArray = other instanceof Float32Array;
  28012. // use non-loop method when the source is Float32Array
  28013. if (isSrcTypedArray) {
  28014. var ret32 = new Float32Array(len);
  28015. ret32.set(source);
  28016. ret32.set(other, source.length);
  28017. return ret32;
  28018. // source is number[], when other is also use concat
  28019. }
  28020. else if (!isOthTypedArray) {
  28021. return source.concat(other);
  28022. // source is a number[], but other is a Float32Array, loop required
  28023. }
  28024. else {
  28025. var ret = source.slice(0); // copy source to a separate array
  28026. for (var i = 0, len = other.length; i < len; i++) {
  28027. ret.push(other[i]);
  28028. }
  28029. return ret;
  28030. }
  28031. };
  28032. /**
  28033. * Serializes the VertexData.
  28034. * Returns a serialized object.
  28035. */
  28036. VertexData.prototype.serialize = function () {
  28037. var serializationObject = this.serialize();
  28038. if (this.positions) {
  28039. serializationObject.positions = this.positions;
  28040. }
  28041. if (this.normals) {
  28042. serializationObject.normals = this.normals;
  28043. }
  28044. if (this.tangents) {
  28045. serializationObject.tangents = this.tangents;
  28046. }
  28047. if (this.uvs) {
  28048. serializationObject.uvs = this.uvs;
  28049. }
  28050. if (this.uvs2) {
  28051. serializationObject.uvs2 = this.uvs2;
  28052. }
  28053. if (this.uvs3) {
  28054. serializationObject.uvs3 = this.uvs3;
  28055. }
  28056. if (this.uvs4) {
  28057. serializationObject.uvs4 = this.uvs4;
  28058. }
  28059. if (this.uvs5) {
  28060. serializationObject.uvs5 = this.uvs5;
  28061. }
  28062. if (this.uvs6) {
  28063. serializationObject.uvs6 = this.uvs6;
  28064. }
  28065. if (this.colors) {
  28066. serializationObject.colors = this.colors;
  28067. }
  28068. if (this.matricesIndices) {
  28069. serializationObject.matricesIndices = this.matricesIndices;
  28070. serializationObject.matricesIndices._isExpanded = true;
  28071. }
  28072. if (this.matricesWeights) {
  28073. serializationObject.matricesWeights = this.matricesWeights;
  28074. }
  28075. if (this.matricesIndicesExtra) {
  28076. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28077. serializationObject.matricesIndicesExtra._isExpanded = true;
  28078. }
  28079. if (this.matricesWeightsExtra) {
  28080. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28081. }
  28082. serializationObject.indices = this.indices;
  28083. return serializationObject;
  28084. };
  28085. // Statics
  28086. /**
  28087. * Returns the object VertexData associated to the passed mesh.
  28088. */
  28089. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28090. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28091. };
  28092. /**
  28093. * Returns the object VertexData associated to the passed geometry.
  28094. */
  28095. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28096. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28097. };
  28098. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28099. var result = new VertexData();
  28100. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28101. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28102. }
  28103. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28104. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28105. }
  28106. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28107. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28108. }
  28109. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28110. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28111. }
  28112. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28113. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28114. }
  28115. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28116. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28117. }
  28118. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28119. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28120. }
  28121. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28122. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28123. }
  28124. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28125. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28126. }
  28127. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28128. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28129. }
  28130. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28131. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28132. }
  28133. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28134. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28135. }
  28136. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28137. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28138. }
  28139. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28140. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28141. }
  28142. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28143. return result;
  28144. };
  28145. /**
  28146. * Creates the vertexData of the Ribbon.
  28147. */
  28148. VertexData.CreateRibbon = function (options) {
  28149. var pathArray = options.pathArray;
  28150. var closeArray = options.closeArray || false;
  28151. var closePath = options.closePath || false;
  28152. var invertUV = options.invertUV || false;
  28153. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28154. var offset = options.offset || defaultOffset;
  28155. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28156. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28157. var customUV = options.uvs;
  28158. var customColors = options.colors;
  28159. var positions = [];
  28160. var indices = [];
  28161. var normals = [];
  28162. var uvs = [];
  28163. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28164. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28165. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28166. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28167. var minlg; // minimal length among all paths from pathArray
  28168. var lg = []; // array of path lengths : nb of vertex per path
  28169. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28170. var p; // path iterator
  28171. var i; // point iterator
  28172. var j; // point iterator
  28173. // if single path in pathArray
  28174. if (pathArray.length < 2) {
  28175. var ar1 = [];
  28176. var ar2 = [];
  28177. for (i = 0; i < pathArray[0].length - offset; i++) {
  28178. ar1.push(pathArray[0][i]);
  28179. ar2.push(pathArray[0][i + offset]);
  28180. }
  28181. pathArray = [ar1, ar2];
  28182. }
  28183. // positions and horizontal distances (u)
  28184. var idc = 0;
  28185. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28186. var path;
  28187. var l;
  28188. minlg = pathArray[0].length;
  28189. var vectlg;
  28190. var dist;
  28191. for (p = 0; p < pathArray.length; p++) {
  28192. uTotalDistance[p] = 0;
  28193. us[p] = [0];
  28194. path = pathArray[p];
  28195. l = path.length;
  28196. minlg = (minlg < l) ? minlg : l;
  28197. j = 0;
  28198. while (j < l) {
  28199. positions.push(path[j].x, path[j].y, path[j].z);
  28200. if (j > 0) {
  28201. vectlg = path[j].subtract(path[j - 1]).length();
  28202. dist = vectlg + uTotalDistance[p];
  28203. us[p].push(dist);
  28204. uTotalDistance[p] = dist;
  28205. }
  28206. j++;
  28207. }
  28208. if (closePath) {
  28209. j--;
  28210. positions.push(path[0].x, path[0].y, path[0].z);
  28211. vectlg = path[j].subtract(path[0]).length();
  28212. dist = vectlg + uTotalDistance[p];
  28213. us[p].push(dist);
  28214. uTotalDistance[p] = dist;
  28215. }
  28216. lg[p] = l + closePathCorr;
  28217. idx[p] = idc;
  28218. idc += (l + closePathCorr);
  28219. }
  28220. // vertical distances (v)
  28221. var path1;
  28222. var path2;
  28223. var vertex1 = null;
  28224. var vertex2 = null;
  28225. for (i = 0; i < minlg + closePathCorr; i++) {
  28226. vTotalDistance[i] = 0;
  28227. vs[i] = [0];
  28228. for (p = 0; p < pathArray.length - 1; p++) {
  28229. path1 = pathArray[p];
  28230. path2 = pathArray[p + 1];
  28231. if (i === minlg) {
  28232. vertex1 = path1[0];
  28233. vertex2 = path2[0];
  28234. }
  28235. else {
  28236. vertex1 = path1[i];
  28237. vertex2 = path2[i];
  28238. }
  28239. vectlg = vertex2.subtract(vertex1).length();
  28240. dist = vectlg + vTotalDistance[i];
  28241. vs[i].push(dist);
  28242. vTotalDistance[i] = dist;
  28243. }
  28244. if (closeArray && vertex2 && vertex1) {
  28245. path1 = pathArray[p];
  28246. path2 = pathArray[0];
  28247. if (i === minlg) {
  28248. vertex2 = path2[0];
  28249. }
  28250. vectlg = vertex2.subtract(vertex1).length();
  28251. dist = vectlg + vTotalDistance[i];
  28252. vTotalDistance[i] = dist;
  28253. }
  28254. }
  28255. // uvs
  28256. var u;
  28257. var v;
  28258. if (customUV) {
  28259. for (p = 0; p < customUV.length; p++) {
  28260. uvs.push(customUV[p].x, customUV[p].y);
  28261. }
  28262. }
  28263. else {
  28264. for (p = 0; p < pathArray.length; p++) {
  28265. for (i = 0; i < minlg + closePathCorr; i++) {
  28266. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28267. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28268. if (invertUV) {
  28269. uvs.push(v, u);
  28270. }
  28271. else {
  28272. uvs.push(u, v);
  28273. }
  28274. }
  28275. }
  28276. }
  28277. // indices
  28278. p = 0; // path index
  28279. var pi = 0; // positions array index
  28280. var l1 = lg[p] - 1; // path1 length
  28281. var l2 = lg[p + 1] - 1; // path2 length
  28282. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28283. var shft = idx[1] - idx[0]; // shift
  28284. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28285. while (pi <= min && p < path1nb) {
  28286. // 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
  28287. indices.push(pi, pi + shft, pi + 1);
  28288. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28289. pi += 1;
  28290. if (pi === min) {
  28291. p++;
  28292. if (p === lg.length - 1) {
  28293. shft = idx[0] - idx[p];
  28294. l1 = lg[p] - 1;
  28295. l2 = lg[0] - 1;
  28296. }
  28297. else {
  28298. shft = idx[p + 1] - idx[p];
  28299. l1 = lg[p] - 1;
  28300. l2 = lg[p + 1] - 1;
  28301. }
  28302. pi = idx[p];
  28303. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28304. }
  28305. }
  28306. // normals
  28307. VertexData.ComputeNormals(positions, indices, normals);
  28308. if (closePath) {
  28309. var indexFirst = 0;
  28310. var indexLast = 0;
  28311. for (p = 0; p < pathArray.length; p++) {
  28312. indexFirst = idx[p] * 3;
  28313. if (p + 1 < pathArray.length) {
  28314. indexLast = (idx[p + 1] - 1) * 3;
  28315. }
  28316. else {
  28317. indexLast = normals.length - 3;
  28318. }
  28319. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28320. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28321. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28322. normals[indexLast] = normals[indexFirst];
  28323. normals[indexLast + 1] = normals[indexFirst + 1];
  28324. normals[indexLast + 2] = normals[indexFirst + 2];
  28325. }
  28326. }
  28327. // sides
  28328. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28329. // Colors
  28330. var colors = null;
  28331. if (customColors) {
  28332. colors = new Float32Array(customColors.length * 4);
  28333. for (var c = 0; c < customColors.length; c++) {
  28334. colors[c * 4] = customColors[c].r;
  28335. colors[c * 4 + 1] = customColors[c].g;
  28336. colors[c * 4 + 2] = customColors[c].b;
  28337. colors[c * 4 + 3] = customColors[c].a;
  28338. }
  28339. }
  28340. // Result
  28341. var vertexData = new VertexData();
  28342. var positions32 = new Float32Array(positions);
  28343. var normals32 = new Float32Array(normals);
  28344. var uvs32 = new Float32Array(uvs);
  28345. vertexData.indices = indices;
  28346. vertexData.positions = positions32;
  28347. vertexData.normals = normals32;
  28348. vertexData.uvs = uvs32;
  28349. if (colors) {
  28350. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28351. }
  28352. if (closePath) {
  28353. vertexData._idx = idx;
  28354. }
  28355. return vertexData;
  28356. };
  28357. /**
  28358. * Creates the VertexData of the Box.
  28359. */
  28360. VertexData.CreateBox = function (options) {
  28361. var normalsSource = [
  28362. new BABYLON.Vector3(0, 0, 1),
  28363. new BABYLON.Vector3(0, 0, -1),
  28364. new BABYLON.Vector3(1, 0, 0),
  28365. new BABYLON.Vector3(-1, 0, 0),
  28366. new BABYLON.Vector3(0, 1, 0),
  28367. new BABYLON.Vector3(0, -1, 0)
  28368. ];
  28369. var indices = [];
  28370. var positions = [];
  28371. var normals = [];
  28372. var uvs = [];
  28373. var width = options.width || options.size || 1;
  28374. var height = options.height || options.size || 1;
  28375. var depth = options.depth || options.size || 1;
  28376. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28377. var faceUV = options.faceUV || new Array(6);
  28378. var faceColors = options.faceColors;
  28379. var colors = [];
  28380. // default face colors and UV if undefined
  28381. for (var f = 0; f < 6; f++) {
  28382. if (faceUV[f] === undefined) {
  28383. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28384. }
  28385. if (faceColors && faceColors[f] === undefined) {
  28386. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28387. }
  28388. }
  28389. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28390. // Create each face in turn.
  28391. for (var index = 0; index < normalsSource.length; index++) {
  28392. var normal = normalsSource[index];
  28393. // Get two vectors perpendicular to the face normal and to each other.
  28394. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28395. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28396. // Six indices (two triangles) per face.
  28397. var verticesLength = positions.length / 3;
  28398. indices.push(verticesLength);
  28399. indices.push(verticesLength + 1);
  28400. indices.push(verticesLength + 2);
  28401. indices.push(verticesLength);
  28402. indices.push(verticesLength + 2);
  28403. indices.push(verticesLength + 3);
  28404. // Four vertices per face.
  28405. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28406. positions.push(vertex.x, vertex.y, vertex.z);
  28407. normals.push(normal.x, normal.y, normal.z);
  28408. uvs.push(faceUV[index].z, faceUV[index].w);
  28409. if (faceColors) {
  28410. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28411. }
  28412. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28413. positions.push(vertex.x, vertex.y, vertex.z);
  28414. normals.push(normal.x, normal.y, normal.z);
  28415. uvs.push(faceUV[index].x, faceUV[index].w);
  28416. if (faceColors) {
  28417. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28418. }
  28419. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28420. positions.push(vertex.x, vertex.y, vertex.z);
  28421. normals.push(normal.x, normal.y, normal.z);
  28422. uvs.push(faceUV[index].x, faceUV[index].y);
  28423. if (faceColors) {
  28424. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28425. }
  28426. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28427. positions.push(vertex.x, vertex.y, vertex.z);
  28428. normals.push(normal.x, normal.y, normal.z);
  28429. uvs.push(faceUV[index].z, faceUV[index].y);
  28430. if (faceColors) {
  28431. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28432. }
  28433. }
  28434. // sides
  28435. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28436. // Result
  28437. var vertexData = new VertexData();
  28438. vertexData.indices = indices;
  28439. vertexData.positions = positions;
  28440. vertexData.normals = normals;
  28441. vertexData.uvs = uvs;
  28442. if (faceColors) {
  28443. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28444. vertexData.colors = totalColors;
  28445. }
  28446. return vertexData;
  28447. };
  28448. /**
  28449. * Creates the VertexData of the Sphere.
  28450. */
  28451. VertexData.CreateSphere = function (options) {
  28452. var segments = options.segments || 32;
  28453. var diameterX = options.diameterX || options.diameter || 1;
  28454. var diameterY = options.diameterY || options.diameter || 1;
  28455. var diameterZ = options.diameterZ || options.diameter || 1;
  28456. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28457. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28458. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28459. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28460. var totalZRotationSteps = 2 + segments;
  28461. var totalYRotationSteps = 2 * totalZRotationSteps;
  28462. var indices = [];
  28463. var positions = [];
  28464. var normals = [];
  28465. var uvs = [];
  28466. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28467. var normalizedZ = zRotationStep / totalZRotationSteps;
  28468. var angleZ = normalizedZ * Math.PI * slice;
  28469. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28470. var normalizedY = yRotationStep / totalYRotationSteps;
  28471. var angleY = normalizedY * Math.PI * 2 * arc;
  28472. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28473. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28474. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28475. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28476. var vertex = complete.multiply(radius);
  28477. var normal = complete.divide(radius).normalize();
  28478. positions.push(vertex.x, vertex.y, vertex.z);
  28479. normals.push(normal.x, normal.y, normal.z);
  28480. uvs.push(normalizedY, normalizedZ);
  28481. }
  28482. if (zRotationStep > 0) {
  28483. var verticesCount = positions.length / 3;
  28484. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28485. indices.push((firstIndex));
  28486. indices.push((firstIndex + 1));
  28487. indices.push(firstIndex + totalYRotationSteps + 1);
  28488. indices.push((firstIndex + totalYRotationSteps + 1));
  28489. indices.push((firstIndex + 1));
  28490. indices.push((firstIndex + totalYRotationSteps + 2));
  28491. }
  28492. }
  28493. }
  28494. // Sides
  28495. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28496. // Result
  28497. var vertexData = new VertexData();
  28498. vertexData.indices = indices;
  28499. vertexData.positions = positions;
  28500. vertexData.normals = normals;
  28501. vertexData.uvs = uvs;
  28502. return vertexData;
  28503. };
  28504. /**
  28505. * Creates the VertexData of the Cylinder or Cone.
  28506. */
  28507. VertexData.CreateCylinder = function (options) {
  28508. var height = options.height || 2;
  28509. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28510. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28511. var tessellation = options.tessellation || 24;
  28512. var subdivisions = options.subdivisions || 1;
  28513. var hasRings = options.hasRings ? true : false;
  28514. var enclose = options.enclose ? true : false;
  28515. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28516. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28517. var faceUV = options.faceUV || new Array(3);
  28518. var faceColors = options.faceColors;
  28519. // default face colors and UV if undefined
  28520. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28521. var ringNb = (hasRings) ? subdivisions : 1;
  28522. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28523. var f;
  28524. for (f = 0; f < surfaceNb; f++) {
  28525. if (faceColors && faceColors[f] === undefined) {
  28526. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28527. }
  28528. }
  28529. for (f = 0; f < surfaceNb; f++) {
  28530. if (faceUV && faceUV[f] === undefined) {
  28531. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28532. }
  28533. }
  28534. var indices = new Array();
  28535. var positions = new Array();
  28536. var normals = new Array();
  28537. var uvs = new Array();
  28538. var colors = new Array();
  28539. var angle_step = Math.PI * 2 * arc / tessellation;
  28540. var angle;
  28541. var h;
  28542. var radius;
  28543. var tan = (diameterBottom - diameterTop) / 2 / height;
  28544. var ringVertex = BABYLON.Vector3.Zero();
  28545. var ringNormal = BABYLON.Vector3.Zero();
  28546. var ringFirstVertex = BABYLON.Vector3.Zero();
  28547. var ringFirstNormal = BABYLON.Vector3.Zero();
  28548. var quadNormal = BABYLON.Vector3.Zero();
  28549. var Y = BABYLON.Axis.Y;
  28550. // positions, normals, uvs
  28551. var i;
  28552. var j;
  28553. var r;
  28554. var ringIdx = 1;
  28555. var s = 1; // surface index
  28556. var cs = 0;
  28557. var v = 0;
  28558. for (i = 0; i <= subdivisions; i++) {
  28559. h = i / subdivisions;
  28560. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28561. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28562. for (r = 0; r < ringIdx; r++) {
  28563. if (hasRings) {
  28564. s += r;
  28565. }
  28566. if (enclose) {
  28567. s += 2 * r;
  28568. }
  28569. for (j = 0; j <= tessellation; j++) {
  28570. angle = j * angle_step;
  28571. // position
  28572. ringVertex.x = Math.cos(-angle) * radius;
  28573. ringVertex.y = -height / 2 + h * height;
  28574. ringVertex.z = Math.sin(-angle) * radius;
  28575. // normal
  28576. if (diameterTop === 0 && i === subdivisions) {
  28577. // if no top cap, reuse former normals
  28578. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28579. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28580. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28581. }
  28582. else {
  28583. ringNormal.x = ringVertex.x;
  28584. ringNormal.z = ringVertex.z;
  28585. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28586. ringNormal.normalize();
  28587. }
  28588. // keep first ring vertex values for enclose
  28589. if (j === 0) {
  28590. ringFirstVertex.copyFrom(ringVertex);
  28591. ringFirstNormal.copyFrom(ringNormal);
  28592. }
  28593. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28594. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28595. if (hasRings) {
  28596. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28597. }
  28598. else {
  28599. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28600. }
  28601. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28602. if (faceColors) {
  28603. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28604. }
  28605. }
  28606. // if enclose, add four vertices and their dedicated normals
  28607. if (arc !== 1 && enclose) {
  28608. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28609. positions.push(0, ringVertex.y, 0);
  28610. positions.push(0, ringVertex.y, 0);
  28611. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28612. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28613. quadNormal.normalize();
  28614. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28615. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28616. quadNormal.normalize();
  28617. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28618. if (hasRings) {
  28619. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28620. }
  28621. else {
  28622. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28623. }
  28624. uvs.push(faceUV[s + 1].x, v);
  28625. uvs.push(faceUV[s + 1].z, v);
  28626. if (hasRings) {
  28627. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28628. }
  28629. else {
  28630. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28631. }
  28632. uvs.push(faceUV[s + 2].x, v);
  28633. uvs.push(faceUV[s + 2].z, v);
  28634. if (faceColors) {
  28635. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28636. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28637. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28638. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28639. }
  28640. }
  28641. if (cs !== s) {
  28642. cs = s;
  28643. }
  28644. }
  28645. }
  28646. // indices
  28647. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28648. var s;
  28649. i = 0;
  28650. for (s = 0; s < subdivisions; s++) {
  28651. var i0 = 0;
  28652. var i1 = 0;
  28653. var i2 = 0;
  28654. var i3 = 0;
  28655. for (j = 0; j < tessellation; j++) {
  28656. i0 = i * (e + 1) + j;
  28657. i1 = (i + 1) * (e + 1) + j;
  28658. i2 = i * (e + 1) + (j + 1);
  28659. i3 = (i + 1) * (e + 1) + (j + 1);
  28660. indices.push(i0, i1, i2);
  28661. indices.push(i3, i2, i1);
  28662. }
  28663. if (arc !== 1 && enclose) {
  28664. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28665. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28666. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28667. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28668. }
  28669. i = (hasRings) ? (i + 2) : (i + 1);
  28670. }
  28671. // Caps
  28672. var createCylinderCap = function (isTop) {
  28673. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28674. if (radius === 0) {
  28675. return;
  28676. }
  28677. // Cap positions, normals & uvs
  28678. var angle;
  28679. var circleVector;
  28680. var i;
  28681. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28682. var c = null;
  28683. if (faceColors) {
  28684. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28685. }
  28686. // cap center
  28687. var vbase = positions.length / 3;
  28688. var offset = isTop ? height / 2 : -height / 2;
  28689. var center = new BABYLON.Vector3(0, offset, 0);
  28690. positions.push(center.x, center.y, center.z);
  28691. normals.push(0, isTop ? 1 : -1, 0);
  28692. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28693. if (c) {
  28694. colors.push(c.r, c.g, c.b, c.a);
  28695. }
  28696. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28697. for (i = 0; i <= tessellation; i++) {
  28698. angle = Math.PI * 2 * i * arc / tessellation;
  28699. var cos = Math.cos(-angle);
  28700. var sin = Math.sin(-angle);
  28701. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28702. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28703. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28704. normals.push(0, isTop ? 1 : -1, 0);
  28705. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28706. if (c) {
  28707. colors.push(c.r, c.g, c.b, c.a);
  28708. }
  28709. }
  28710. // Cap indices
  28711. for (i = 0; i < tessellation; i++) {
  28712. if (!isTop) {
  28713. indices.push(vbase);
  28714. indices.push(vbase + (i + 1));
  28715. indices.push(vbase + (i + 2));
  28716. }
  28717. else {
  28718. indices.push(vbase);
  28719. indices.push(vbase + (i + 2));
  28720. indices.push(vbase + (i + 1));
  28721. }
  28722. }
  28723. };
  28724. // add caps to geometry
  28725. createCylinderCap(false);
  28726. createCylinderCap(true);
  28727. // Sides
  28728. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28729. var vertexData = new VertexData();
  28730. vertexData.indices = indices;
  28731. vertexData.positions = positions;
  28732. vertexData.normals = normals;
  28733. vertexData.uvs = uvs;
  28734. if (faceColors) {
  28735. vertexData.colors = colors;
  28736. }
  28737. return vertexData;
  28738. };
  28739. /**
  28740. * Creates the VertexData of the Torus.
  28741. */
  28742. VertexData.CreateTorus = function (options) {
  28743. var indices = [];
  28744. var positions = [];
  28745. var normals = [];
  28746. var uvs = [];
  28747. var diameter = options.diameter || 1;
  28748. var thickness = options.thickness || 0.5;
  28749. var tessellation = options.tessellation || 16;
  28750. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28751. var stride = tessellation + 1;
  28752. for (var i = 0; i <= tessellation; i++) {
  28753. var u = i / tessellation;
  28754. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28755. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28756. for (var j = 0; j <= tessellation; j++) {
  28757. var v = 1 - j / tessellation;
  28758. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28759. var dx = Math.cos(innerAngle);
  28760. var dy = Math.sin(innerAngle);
  28761. // Create a vertex.
  28762. var normal = new BABYLON.Vector3(dx, dy, 0);
  28763. var position = normal.scale(thickness / 2);
  28764. var textureCoordinate = new BABYLON.Vector2(u, v);
  28765. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28766. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28767. positions.push(position.x, position.y, position.z);
  28768. normals.push(normal.x, normal.y, normal.z);
  28769. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28770. // And create indices for two triangles.
  28771. var nextI = (i + 1) % stride;
  28772. var nextJ = (j + 1) % stride;
  28773. indices.push(i * stride + j);
  28774. indices.push(i * stride + nextJ);
  28775. indices.push(nextI * stride + j);
  28776. indices.push(i * stride + nextJ);
  28777. indices.push(nextI * stride + nextJ);
  28778. indices.push(nextI * stride + j);
  28779. }
  28780. }
  28781. // Sides
  28782. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28783. // Result
  28784. var vertexData = new VertexData();
  28785. vertexData.indices = indices;
  28786. vertexData.positions = positions;
  28787. vertexData.normals = normals;
  28788. vertexData.uvs = uvs;
  28789. return vertexData;
  28790. };
  28791. /**
  28792. * Creates the VertexData of the LineSystem.
  28793. */
  28794. VertexData.CreateLineSystem = function (options) {
  28795. var indices = [];
  28796. var positions = [];
  28797. var lines = options.lines;
  28798. var idx = 0;
  28799. for (var l = 0; l < lines.length; l++) {
  28800. var points = lines[l];
  28801. for (var index = 0; index < points.length; index++) {
  28802. positions.push(points[index].x, points[index].y, points[index].z);
  28803. if (index > 0) {
  28804. indices.push(idx - 1);
  28805. indices.push(idx);
  28806. }
  28807. idx++;
  28808. }
  28809. }
  28810. var vertexData = new VertexData();
  28811. vertexData.indices = indices;
  28812. vertexData.positions = positions;
  28813. return vertexData;
  28814. };
  28815. /**
  28816. * Create the VertexData of the DashedLines.
  28817. */
  28818. VertexData.CreateDashedLines = function (options) {
  28819. var dashSize = options.dashSize || 3;
  28820. var gapSize = options.gapSize || 1;
  28821. var dashNb = options.dashNb || 200;
  28822. var points = options.points;
  28823. var positions = new Array();
  28824. var indices = new Array();
  28825. var curvect = BABYLON.Vector3.Zero();
  28826. var lg = 0;
  28827. var nb = 0;
  28828. var shft = 0;
  28829. var dashshft = 0;
  28830. var curshft = 0;
  28831. var idx = 0;
  28832. var i = 0;
  28833. for (i = 0; i < points.length - 1; i++) {
  28834. points[i + 1].subtractToRef(points[i], curvect);
  28835. lg += curvect.length();
  28836. }
  28837. shft = lg / dashNb;
  28838. dashshft = dashSize * shft / (dashSize + gapSize);
  28839. for (i = 0; i < points.length - 1; i++) {
  28840. points[i + 1].subtractToRef(points[i], curvect);
  28841. nb = Math.floor(curvect.length() / shft);
  28842. curvect.normalize();
  28843. for (var j = 0; j < nb; j++) {
  28844. curshft = shft * j;
  28845. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28846. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28847. indices.push(idx, idx + 1);
  28848. idx += 2;
  28849. }
  28850. }
  28851. // Result
  28852. var vertexData = new VertexData();
  28853. vertexData.positions = positions;
  28854. vertexData.indices = indices;
  28855. return vertexData;
  28856. };
  28857. /**
  28858. * Creates the VertexData of the Ground.
  28859. */
  28860. VertexData.CreateGround = function (options) {
  28861. var indices = [];
  28862. var positions = [];
  28863. var normals = [];
  28864. var uvs = [];
  28865. var row, col;
  28866. var width = options.width || 1;
  28867. var height = options.height || 1;
  28868. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  28869. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  28870. for (row = 0; row <= subdivisionsY; row++) {
  28871. for (col = 0; col <= subdivisionsX; col++) {
  28872. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  28873. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28874. positions.push(position.x, position.y, position.z);
  28875. normals.push(normal.x, normal.y, normal.z);
  28876. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  28877. }
  28878. }
  28879. for (row = 0; row < subdivisionsY; row++) {
  28880. for (col = 0; col < subdivisionsX; col++) {
  28881. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28882. indices.push(col + 1 + row * (subdivisionsX + 1));
  28883. indices.push(col + row * (subdivisionsX + 1));
  28884. indices.push(col + (row + 1) * (subdivisionsX + 1));
  28885. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28886. indices.push(col + row * (subdivisionsX + 1));
  28887. }
  28888. }
  28889. // Result
  28890. var vertexData = new VertexData();
  28891. vertexData.indices = indices;
  28892. vertexData.positions = positions;
  28893. vertexData.normals = normals;
  28894. vertexData.uvs = uvs;
  28895. return vertexData;
  28896. };
  28897. /**
  28898. * Creates the VertexData of the TiledGround.
  28899. */
  28900. VertexData.CreateTiledGround = function (options) {
  28901. var xmin = options.xmin || -1.0;
  28902. var zmin = options.zmin || -1.0;
  28903. var xmax = options.xmax || 1.0;
  28904. var zmax = options.zmax || 1.0;
  28905. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28906. var precision = options.precision || { w: 1, h: 1 };
  28907. var indices = new Array();
  28908. var positions = new Array();
  28909. var normals = new Array();
  28910. var uvs = new Array();
  28911. var row, col, tileRow, tileCol;
  28912. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  28913. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28914. precision.w = (precision.w < 1) ? 1 : precision.w;
  28915. precision.h = (precision.h < 1) ? 1 : precision.h;
  28916. var tileSize = {
  28917. 'w': (xmax - xmin) / subdivisions.w,
  28918. 'h': (zmax - zmin) / subdivisions.h
  28919. };
  28920. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28921. // Indices
  28922. var base = positions.length / 3;
  28923. var rowLength = precision.w + 1;
  28924. for (row = 0; row < precision.h; row++) {
  28925. for (col = 0; col < precision.w; col++) {
  28926. var square = [
  28927. base + col + row * rowLength,
  28928. base + (col + 1) + row * rowLength,
  28929. base + (col + 1) + (row + 1) * rowLength,
  28930. base + col + (row + 1) * rowLength
  28931. ];
  28932. indices.push(square[1]);
  28933. indices.push(square[2]);
  28934. indices.push(square[3]);
  28935. indices.push(square[0]);
  28936. indices.push(square[1]);
  28937. indices.push(square[3]);
  28938. }
  28939. }
  28940. // Position, normals and uvs
  28941. var position = BABYLON.Vector3.Zero();
  28942. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28943. for (row = 0; row <= precision.h; row++) {
  28944. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28945. for (col = 0; col <= precision.w; col++) {
  28946. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28947. position.y = 0;
  28948. positions.push(position.x, position.y, position.z);
  28949. normals.push(normal.x, normal.y, normal.z);
  28950. uvs.push(col / precision.w, row / precision.h);
  28951. }
  28952. }
  28953. }
  28954. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28955. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28956. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28957. }
  28958. }
  28959. // Result
  28960. var vertexData = new VertexData();
  28961. vertexData.indices = indices;
  28962. vertexData.positions = positions;
  28963. vertexData.normals = normals;
  28964. vertexData.uvs = uvs;
  28965. return vertexData;
  28966. };
  28967. /**
  28968. * Creates the VertexData of the Ground designed from a heightmap.
  28969. */
  28970. VertexData.CreateGroundFromHeightMap = function (options) {
  28971. var indices = [];
  28972. var positions = [];
  28973. var normals = [];
  28974. var uvs = [];
  28975. var row, col;
  28976. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  28977. // Vertices
  28978. for (row = 0; row <= options.subdivisions; row++) {
  28979. for (col = 0; col <= options.subdivisions; col++) {
  28980. 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));
  28981. // Compute height
  28982. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28983. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28984. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28985. var r = options.buffer[pos] / 255.0;
  28986. var g = options.buffer[pos + 1] / 255.0;
  28987. var b = options.buffer[pos + 2] / 255.0;
  28988. var gradient = r * filter.r + g * filter.g + b * filter.b;
  28989. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28990. // Add vertex
  28991. positions.push(position.x, position.y, position.z);
  28992. normals.push(0, 0, 0);
  28993. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28994. }
  28995. }
  28996. // Indices
  28997. for (row = 0; row < options.subdivisions; row++) {
  28998. for (col = 0; col < options.subdivisions; col++) {
  28999. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29000. indices.push(col + 1 + row * (options.subdivisions + 1));
  29001. indices.push(col + row * (options.subdivisions + 1));
  29002. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29003. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29004. indices.push(col + row * (options.subdivisions + 1));
  29005. }
  29006. }
  29007. // Normals
  29008. VertexData.ComputeNormals(positions, indices, normals);
  29009. // Result
  29010. var vertexData = new VertexData();
  29011. vertexData.indices = indices;
  29012. vertexData.positions = positions;
  29013. vertexData.normals = normals;
  29014. vertexData.uvs = uvs;
  29015. return vertexData;
  29016. };
  29017. /**
  29018. * Creates the VertexData of the Plane.
  29019. */
  29020. VertexData.CreatePlane = function (options) {
  29021. var indices = [];
  29022. var positions = [];
  29023. var normals = [];
  29024. var uvs = [];
  29025. var width = options.width || options.size || 1;
  29026. var height = options.height || options.size || 1;
  29027. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29028. // Vertices
  29029. var halfWidth = width / 2.0;
  29030. var halfHeight = height / 2.0;
  29031. positions.push(-halfWidth, -halfHeight, 0);
  29032. normals.push(0, 0, -1.0);
  29033. uvs.push(0.0, 0.0);
  29034. positions.push(halfWidth, -halfHeight, 0);
  29035. normals.push(0, 0, -1.0);
  29036. uvs.push(1.0, 0.0);
  29037. positions.push(halfWidth, halfHeight, 0);
  29038. normals.push(0, 0, -1.0);
  29039. uvs.push(1.0, 1.0);
  29040. positions.push(-halfWidth, halfHeight, 0);
  29041. normals.push(0, 0, -1.0);
  29042. uvs.push(0.0, 1.0);
  29043. // Indices
  29044. indices.push(0);
  29045. indices.push(1);
  29046. indices.push(2);
  29047. indices.push(0);
  29048. indices.push(2);
  29049. indices.push(3);
  29050. // Sides
  29051. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29052. // Result
  29053. var vertexData = new VertexData();
  29054. vertexData.indices = indices;
  29055. vertexData.positions = positions;
  29056. vertexData.normals = normals;
  29057. vertexData.uvs = uvs;
  29058. return vertexData;
  29059. };
  29060. /**
  29061. * Creates the VertexData of the Disc or regular Polygon.
  29062. */
  29063. VertexData.CreateDisc = function (options) {
  29064. var positions = new Array();
  29065. var indices = new Array();
  29066. var normals = new Array();
  29067. var uvs = new Array();
  29068. var radius = options.radius || 0.5;
  29069. var tessellation = options.tessellation || 64;
  29070. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29071. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29072. // positions and uvs
  29073. positions.push(0, 0, 0); // disc center first
  29074. uvs.push(0.5, 0.5);
  29075. var theta = Math.PI * 2 * arc;
  29076. var step = theta / tessellation;
  29077. for (var a = 0; a < theta; a += step) {
  29078. var x = Math.cos(a);
  29079. var y = Math.sin(a);
  29080. var u = (x + 1) / 2;
  29081. var v = (1 - y) / 2;
  29082. positions.push(radius * x, radius * y, 0);
  29083. uvs.push(u, v);
  29084. }
  29085. if (arc === 1) {
  29086. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29087. uvs.push(uvs[2], uvs[3]);
  29088. }
  29089. //indices
  29090. var vertexNb = positions.length / 3;
  29091. for (var i = 1; i < vertexNb - 1; i++) {
  29092. indices.push(i + 1, 0, i);
  29093. }
  29094. // result
  29095. VertexData.ComputeNormals(positions, indices, normals);
  29096. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29097. var vertexData = new VertexData();
  29098. vertexData.indices = indices;
  29099. vertexData.positions = positions;
  29100. vertexData.normals = normals;
  29101. vertexData.uvs = uvs;
  29102. return vertexData;
  29103. };
  29104. /**
  29105. * Re-creates the VertexData of the Polygon for sideOrientation.
  29106. */
  29107. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29108. var faceUV = fUV || new Array(3);
  29109. var faceColors = fColors;
  29110. var colors = [];
  29111. // default face colors and UV if undefined
  29112. for (var f = 0; f < 3; f++) {
  29113. if (faceUV[f] === undefined) {
  29114. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29115. }
  29116. if (faceColors && faceColors[f] === undefined) {
  29117. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29118. }
  29119. }
  29120. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29121. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29122. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29123. var indices = polygon.getIndices();
  29124. // set face colours and textures
  29125. var idx = 0;
  29126. var face = 0;
  29127. for (var index = 0; index < normals.length; index += 3) {
  29128. //Edge Face no. 1
  29129. if (Math.abs(normals[index + 1]) < 0.001) {
  29130. face = 1;
  29131. }
  29132. //Top Face no. 0
  29133. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29134. face = 0;
  29135. }
  29136. //Bottom Face no. 2
  29137. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29138. face = 2;
  29139. }
  29140. idx = index / 3;
  29141. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29142. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29143. if (faceColors) {
  29144. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29145. }
  29146. }
  29147. // sides
  29148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29149. // Result
  29150. var vertexData = new VertexData();
  29151. vertexData.indices = indices;
  29152. vertexData.positions = positions;
  29153. vertexData.normals = normals;
  29154. vertexData.uvs = uvs;
  29155. if (faceColors) {
  29156. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29157. vertexData.colors = totalColors;
  29158. }
  29159. return vertexData;
  29160. };
  29161. /**
  29162. * Creates the VertexData of the IcoSphere.
  29163. */
  29164. VertexData.CreateIcoSphere = function (options) {
  29165. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29166. var radius = options.radius || 1;
  29167. var flat = (options.flat === undefined) ? true : options.flat;
  29168. var subdivisions = options.subdivisions || 4;
  29169. var radiusX = options.radiusX || radius;
  29170. var radiusY = options.radiusY || radius;
  29171. var radiusZ = options.radiusZ || radius;
  29172. var t = (1 + Math.sqrt(5)) / 2;
  29173. // 12 vertex x,y,z
  29174. var ico_vertices = [
  29175. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29176. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29177. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29178. ];
  29179. // index of 3 vertex makes a face of icopshere
  29180. var ico_indices = [
  29181. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29182. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29183. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29184. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29185. ];
  29186. // vertex for uv have aliased position, not for UV
  29187. var vertices_unalias_id = [
  29188. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29189. // vertex alias
  29190. 0,
  29191. 2,
  29192. 3,
  29193. 3,
  29194. 3,
  29195. 4,
  29196. 7,
  29197. 8,
  29198. 9,
  29199. 9,
  29200. 10,
  29201. 11 // 23: B + 12
  29202. ];
  29203. // uv as integer step (not pixels !)
  29204. var ico_vertexuv = [
  29205. 5, 1, 3, 1, 6, 4, 0, 0,
  29206. 5, 3, 4, 2, 2, 2, 4, 0,
  29207. 2, 0, 1, 1, 6, 0, 6, 2,
  29208. // vertex alias (for same vertex on different faces)
  29209. 0, 4,
  29210. 3, 3,
  29211. 4, 4,
  29212. 3, 1,
  29213. 4, 2,
  29214. 4, 4,
  29215. 0, 2,
  29216. 1, 1,
  29217. 2, 2,
  29218. 3, 3,
  29219. 1, 3,
  29220. 2, 4 // 23: B + 12
  29221. ];
  29222. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29223. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29224. // First island of uv mapping
  29225. // v = 4h 3+ 2
  29226. // v = 3h 9+ 4
  29227. // v = 2h 9+ 5 B
  29228. // v = 1h 9 1 0
  29229. // v = 0h 3 8 7 A
  29230. // u = 0 1 2 3 4 5 6 *a
  29231. // Second island of uv mapping
  29232. // v = 4h 0+ B+ 4+
  29233. // v = 3h A+ 2+
  29234. // v = 2h 7+ 6 3+
  29235. // v = 1h 8+ 3+
  29236. // v = 0h
  29237. // u = 0 1 2 3 4 5 6 *a
  29238. // Face layout on texture UV mapping
  29239. // ============
  29240. // \ 4 /\ 16 / ======
  29241. // \ / \ / /\ 11 /
  29242. // \/ 7 \/ / \ /
  29243. // ======= / 10 \/
  29244. // /\ 17 /\ =======
  29245. // / \ / \ \ 15 /\
  29246. // / 8 \/ 12 \ \ / \
  29247. // ============ \/ 6 \
  29248. // \ 18 /\ ============
  29249. // \ / \ \ 5 /\ 0 /
  29250. // \/ 13 \ \ / \ /
  29251. // ======= \/ 1 \/
  29252. // =============
  29253. // /\ 19 /\ 2 /\
  29254. // / \ / \ / \
  29255. // / 14 \/ 9 \/ 3 \
  29256. // ===================
  29257. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29258. var ustep = 138 / 1024;
  29259. var vstep = 239 / 1024;
  29260. var uoffset = 60 / 1024;
  29261. var voffset = 26 / 1024;
  29262. // Second island should have margin, not to touch the first island
  29263. // avoid any borderline artefact in pixel rounding
  29264. var island_u_offset = -40 / 1024;
  29265. var island_v_offset = +20 / 1024;
  29266. // face is either island 0 or 1 :
  29267. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29268. var island = [
  29269. 0, 0, 0, 0, 1,
  29270. 0, 0, 1, 1, 0,
  29271. 0, 0, 1, 1, 0,
  29272. 0, 1, 1, 1, 0 // 15 - 19
  29273. ];
  29274. var indices = new Array();
  29275. var positions = new Array();
  29276. var normals = new Array();
  29277. var uvs = new Array();
  29278. var current_indice = 0;
  29279. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29280. var face_vertex_pos = new Array(3);
  29281. var face_vertex_uv = new Array(3);
  29282. var v012;
  29283. for (v012 = 0; v012 < 3; v012++) {
  29284. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29285. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29286. }
  29287. // create all with normals
  29288. for (var face = 0; face < 20; face++) {
  29289. // 3 vertex per face
  29290. for (v012 = 0; v012 < 3; v012++) {
  29291. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29292. var v_id = ico_indices[3 * face + v012];
  29293. // vertex have 3D position (x,y,z)
  29294. 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]);
  29295. // Normalize to get normal, then scale to radius
  29296. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29297. // uv Coordinates from vertex ID
  29298. 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);
  29299. }
  29300. // Subdivide the face (interpolate pos, norm, uv)
  29301. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29302. // - norm is linear interpolation of vertex corner normal
  29303. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29304. // - uv is linear interpolation
  29305. //
  29306. // Topology is as below for sub-divide by 2
  29307. // vertex shown as v0,v1,v2
  29308. // interp index is i1 to progress in range [v0,v1[
  29309. // interp index is i2 to progress in range [v0,v2[
  29310. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29311. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29312. //
  29313. //
  29314. // i2 v2
  29315. // ^ ^
  29316. // / / \
  29317. // / / \
  29318. // / / \
  29319. // / / (0,1) \
  29320. // / #---------\
  29321. // / / \ (0,0)'/ \
  29322. // / / \ / \
  29323. // / / \ / \
  29324. // / / (0,0) \ / (1,0) \
  29325. // / #---------#---------\
  29326. // v0 v1
  29327. //
  29328. // --------------------> i1
  29329. //
  29330. // interp of (i1,i2):
  29331. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29332. // along i1 : lerp(x0,x1, i1/(S-i2))
  29333. //
  29334. // centroid of triangle is needed to get help normal computation
  29335. // (c1,c2) are used for centroid location
  29336. var interp_vertex = function (i1, i2, c1, c2) {
  29337. // vertex is interpolated from
  29338. // - face_vertex_pos[0..2]
  29339. // - face_vertex_uv[0..2]
  29340. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29341. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29342. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29343. pos_interp.normalize();
  29344. var vertex_normal;
  29345. if (flat) {
  29346. // in flat mode, recalculate normal as face centroid normal
  29347. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29348. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29349. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29350. }
  29351. else {
  29352. // in smooth mode, recalculate normal from each single vertex position
  29353. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29354. }
  29355. // Vertex normal need correction due to X,Y,Z radius scaling
  29356. vertex_normal.x /= radiusX;
  29357. vertex_normal.y /= radiusY;
  29358. vertex_normal.z /= radiusZ;
  29359. vertex_normal.normalize();
  29360. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29361. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29362. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29363. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29364. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29365. uvs.push(uv_interp.x, uv_interp.y);
  29366. // push each vertex has member of a face
  29367. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29368. indices.push(current_indice);
  29369. current_indice++;
  29370. };
  29371. for (var i2 = 0; i2 < subdivisions; i2++) {
  29372. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29373. // face : (i1,i2) for /\ :
  29374. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29375. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29376. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29377. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29378. if (i1 + i2 + 1 < subdivisions) {
  29379. // face : (i1,i2)' for \/ :
  29380. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29381. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29382. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29383. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29384. }
  29385. }
  29386. }
  29387. }
  29388. // Sides
  29389. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29390. // Result
  29391. var vertexData = new VertexData();
  29392. vertexData.indices = indices;
  29393. vertexData.positions = positions;
  29394. vertexData.normals = normals;
  29395. vertexData.uvs = uvs;
  29396. return vertexData;
  29397. };
  29398. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29399. /**
  29400. * Creates the VertexData of the Polyhedron.
  29401. */
  29402. VertexData.CreatePolyhedron = function (options) {
  29403. // provided polyhedron types :
  29404. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29405. // 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)
  29406. var polyhedra = [];
  29407. 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]] };
  29408. 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]] };
  29409. polyhedra[2] = {
  29410. 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]],
  29411. 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]]
  29412. };
  29413. polyhedra[3] = {
  29414. 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]],
  29415. 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]]
  29416. };
  29417. polyhedra[4] = {
  29418. 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]],
  29419. 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]]
  29420. };
  29421. 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]] };
  29422. 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]] };
  29423. 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]] };
  29424. 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]] };
  29425. 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]] };
  29426. 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]] };
  29427. 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]] };
  29428. 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]] };
  29429. 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]] };
  29430. polyhedra[14] = {
  29431. 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]],
  29432. 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]]
  29433. };
  29434. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29435. var size = options.size;
  29436. var sizeX = options.sizeX || size || 1;
  29437. var sizeY = options.sizeY || size || 1;
  29438. var sizeZ = options.sizeZ || size || 1;
  29439. var data = options.custom || polyhedra[type];
  29440. var nbfaces = data.face.length;
  29441. var faceUV = options.faceUV || new Array(nbfaces);
  29442. var faceColors = options.faceColors;
  29443. var flat = (options.flat === undefined) ? true : options.flat;
  29444. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29445. var positions = new Array();
  29446. var indices = new Array();
  29447. var normals = new Array();
  29448. var uvs = new Array();
  29449. var colors = new Array();
  29450. var index = 0;
  29451. var faceIdx = 0; // face cursor in the array "indexes"
  29452. var indexes = new Array();
  29453. var i = 0;
  29454. var f = 0;
  29455. var u, v, ang, x, y, tmp;
  29456. // default face colors and UV if undefined
  29457. if (flat) {
  29458. for (f = 0; f < nbfaces; f++) {
  29459. if (faceColors && faceColors[f] === undefined) {
  29460. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29461. }
  29462. if (faceUV && faceUV[f] === undefined) {
  29463. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29464. }
  29465. }
  29466. }
  29467. if (!flat) {
  29468. for (i = 0; i < data.vertex.length; i++) {
  29469. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29470. uvs.push(0, 0);
  29471. }
  29472. for (f = 0; f < nbfaces; f++) {
  29473. for (i = 0; i < data.face[f].length - 2; i++) {
  29474. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29475. }
  29476. }
  29477. }
  29478. else {
  29479. for (f = 0; f < nbfaces; f++) {
  29480. var fl = data.face[f].length; // number of vertices of the current face
  29481. ang = 2 * Math.PI / fl;
  29482. x = 0.5 * Math.tan(ang / 2);
  29483. y = 0.5;
  29484. // positions, uvs, colors
  29485. for (i = 0; i < fl; i++) {
  29486. // positions
  29487. 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);
  29488. indexes.push(index);
  29489. index++;
  29490. // uvs
  29491. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29492. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29493. uvs.push(u, v);
  29494. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29495. y = x * Math.sin(ang) + y * Math.cos(ang);
  29496. x = tmp;
  29497. // colors
  29498. if (faceColors) {
  29499. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29500. }
  29501. }
  29502. // indices from indexes
  29503. for (i = 0; i < fl - 2; i++) {
  29504. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29505. }
  29506. faceIdx += fl;
  29507. }
  29508. }
  29509. VertexData.ComputeNormals(positions, indices, normals);
  29510. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29511. var vertexData = new VertexData();
  29512. vertexData.positions = positions;
  29513. vertexData.indices = indices;
  29514. vertexData.normals = normals;
  29515. vertexData.uvs = uvs;
  29516. if (faceColors && flat) {
  29517. vertexData.colors = colors;
  29518. }
  29519. return vertexData;
  29520. };
  29521. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29522. /**
  29523. * Creates the VertexData of the Torus Knot.
  29524. */
  29525. VertexData.CreateTorusKnot = function (options) {
  29526. var indices = new Array();
  29527. var positions = new Array();
  29528. var normals = new Array();
  29529. var uvs = new Array();
  29530. var radius = options.radius || 2;
  29531. var tube = options.tube || 0.5;
  29532. var radialSegments = options.radialSegments || 32;
  29533. var tubularSegments = options.tubularSegments || 32;
  29534. var p = options.p || 2;
  29535. var q = options.q || 3;
  29536. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29537. // Helper
  29538. var getPos = function (angle) {
  29539. var cu = Math.cos(angle);
  29540. var su = Math.sin(angle);
  29541. var quOverP = q / p * angle;
  29542. var cs = Math.cos(quOverP);
  29543. var tx = radius * (2 + cs) * 0.5 * cu;
  29544. var ty = radius * (2 + cs) * su * 0.5;
  29545. var tz = radius * Math.sin(quOverP) * 0.5;
  29546. return new BABYLON.Vector3(tx, ty, tz);
  29547. };
  29548. // Vertices
  29549. var i;
  29550. var j;
  29551. for (i = 0; i <= radialSegments; i++) {
  29552. var modI = i % radialSegments;
  29553. var u = modI / radialSegments * 2 * p * Math.PI;
  29554. var p1 = getPos(u);
  29555. var p2 = getPos(u + 0.01);
  29556. var tang = p2.subtract(p1);
  29557. var n = p2.add(p1);
  29558. var bitan = BABYLON.Vector3.Cross(tang, n);
  29559. n = BABYLON.Vector3.Cross(bitan, tang);
  29560. bitan.normalize();
  29561. n.normalize();
  29562. for (j = 0; j < tubularSegments; j++) {
  29563. var modJ = j % tubularSegments;
  29564. var v = modJ / tubularSegments * 2 * Math.PI;
  29565. var cx = -tube * Math.cos(v);
  29566. var cy = tube * Math.sin(v);
  29567. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29568. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29569. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29570. uvs.push(i / radialSegments);
  29571. uvs.push(j / tubularSegments);
  29572. }
  29573. }
  29574. for (i = 0; i < radialSegments; i++) {
  29575. for (j = 0; j < tubularSegments; j++) {
  29576. var jNext = (j + 1) % tubularSegments;
  29577. var a = i * tubularSegments + j;
  29578. var b = (i + 1) * tubularSegments + j;
  29579. var c = (i + 1) * tubularSegments + jNext;
  29580. var d = i * tubularSegments + jNext;
  29581. indices.push(d);
  29582. indices.push(b);
  29583. indices.push(a);
  29584. indices.push(d);
  29585. indices.push(c);
  29586. indices.push(b);
  29587. }
  29588. }
  29589. // Normals
  29590. VertexData.ComputeNormals(positions, indices, normals);
  29591. // Sides
  29592. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29593. // Result
  29594. var vertexData = new VertexData();
  29595. vertexData.indices = indices;
  29596. vertexData.positions = positions;
  29597. vertexData.normals = normals;
  29598. vertexData.uvs = uvs;
  29599. return vertexData;
  29600. };
  29601. // Tools
  29602. /**
  29603. * @param {any} - positions (number[] or Float32Array)
  29604. * @param {any} - indices (number[] or Uint16Array)
  29605. * @param {any} - normals (number[] or Float32Array)
  29606. * options (optional) :
  29607. * facetPositions : optional array of facet positions (vector3)
  29608. * facetNormals : optional array of facet normals (vector3)
  29609. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29610. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29611. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29612. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29613. * bInfo : optional bounding info, required for facetPartitioning computation
  29614. */
  29615. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29616. // temporary scalar variables
  29617. var index = 0; // facet index
  29618. var p1p2x = 0.0; // p1p2 vector x coordinate
  29619. var p1p2y = 0.0; // p1p2 vector y coordinate
  29620. var p1p2z = 0.0; // p1p2 vector z coordinate
  29621. var p3p2x = 0.0; // p3p2 vector x coordinate
  29622. var p3p2y = 0.0; // p3p2 vector y coordinate
  29623. var p3p2z = 0.0; // p3p2 vector z coordinate
  29624. var faceNormalx = 0.0; // facet normal x coordinate
  29625. var faceNormaly = 0.0; // facet normal y coordinate
  29626. var faceNormalz = 0.0; // facet normal z coordinate
  29627. var length = 0.0; // facet normal length before normalization
  29628. var v1x = 0; // vector1 x index in the positions array
  29629. var v1y = 0; // vector1 y index in the positions array
  29630. var v1z = 0; // vector1 z index in the positions array
  29631. var v2x = 0; // vector2 x index in the positions array
  29632. var v2y = 0; // vector2 y index in the positions array
  29633. var v2z = 0; // vector2 z index in the positions array
  29634. var v3x = 0; // vector3 x index in the positions array
  29635. var v3y = 0; // vector3 y index in the positions array
  29636. var v3z = 0; // vector3 z index in the positions array
  29637. var computeFacetNormals = false;
  29638. var computeFacetPositions = false;
  29639. var computeFacetPartitioning = false;
  29640. var faceNormalSign = 1;
  29641. var ratio = 0;
  29642. if (options) {
  29643. computeFacetNormals = (options.facetNormals) ? true : false;
  29644. computeFacetPositions = (options.facetPositions) ? true : false;
  29645. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  29646. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  29647. ratio = options.ratio || 0;
  29648. }
  29649. // facetPartitioning reinit if needed
  29650. var xSubRatio = 0;
  29651. var ySubRatio = 0;
  29652. var zSubRatio = 0;
  29653. var subSq = 0;
  29654. if (computeFacetPartitioning && options && options.bbSize) {
  29655. var ox = 0; // X partitioning index for facet position
  29656. var oy = 0; // Y partinioning index for facet position
  29657. var oz = 0; // Z partinioning index for facet position
  29658. var b1x = 0; // X partitioning index for facet v1 vertex
  29659. var b1y = 0; // Y partitioning index for facet v1 vertex
  29660. var b1z = 0; // z partitioning index for facet v1 vertex
  29661. var b2x = 0; // X partitioning index for facet v2 vertex
  29662. var b2y = 0; // Y partitioning index for facet v2 vertex
  29663. var b2z = 0; // Z partitioning index for facet v2 vertex
  29664. var b3x = 0; // X partitioning index for facet v3 vertex
  29665. var b3y = 0; // Y partitioning index for facet v3 vertex
  29666. var b3z = 0; // Z partitioning index for facet v3 vertex
  29667. var block_idx_o = 0; // facet barycenter block index
  29668. var block_idx_v1 = 0; // v1 vertex block index
  29669. var block_idx_v2 = 0; // v2 vertex block index
  29670. var block_idx_v3 = 0; // v3 vertex block index
  29671. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  29672. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  29673. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  29674. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  29675. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  29676. subSq = options.subDiv.max * options.subDiv.max;
  29677. options.facetPartitioning.length = 0;
  29678. }
  29679. // reset the normals
  29680. for (index = 0; index < positions.length; index++) {
  29681. normals[index] = 0.0;
  29682. }
  29683. // Loop : 1 indice triplet = 1 facet
  29684. var nbFaces = indices.length / 3;
  29685. for (index = 0; index < nbFaces; index++) {
  29686. // get the indexes of the coordinates of each vertex of the facet
  29687. v1x = indices[index * 3] * 3;
  29688. v1y = v1x + 1;
  29689. v1z = v1x + 2;
  29690. v2x = indices[index * 3 + 1] * 3;
  29691. v2y = v2x + 1;
  29692. v2z = v2x + 2;
  29693. v3x = indices[index * 3 + 2] * 3;
  29694. v3y = v3x + 1;
  29695. v3z = v3x + 2;
  29696. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  29697. p1p2y = positions[v1y] - positions[v2y];
  29698. p1p2z = positions[v1z] - positions[v2z];
  29699. p3p2x = positions[v3x] - positions[v2x];
  29700. p3p2y = positions[v3y] - positions[v2y];
  29701. p3p2z = positions[v3z] - positions[v2z];
  29702. // compute the face normal with the cross product
  29703. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  29704. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  29705. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  29706. // normalize this normal and store it in the array facetData
  29707. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29708. length = (length === 0) ? 1.0 : length;
  29709. faceNormalx /= length;
  29710. faceNormaly /= length;
  29711. faceNormalz /= length;
  29712. if (computeFacetNormals && options) {
  29713. options.facetNormals[index].x = faceNormalx;
  29714. options.facetNormals[index].y = faceNormaly;
  29715. options.facetNormals[index].z = faceNormalz;
  29716. }
  29717. if (computeFacetPositions && options) {
  29718. // compute and the facet barycenter coordinates in the array facetPositions
  29719. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  29720. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  29721. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  29722. }
  29723. if (computeFacetPartitioning && options) {
  29724. // store the facet indexes in arrays in the main facetPartitioning array :
  29725. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  29726. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  29727. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  29728. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  29729. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29730. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29731. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29732. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29733. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29734. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29735. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29736. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29737. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29738. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  29739. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  29740. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  29741. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  29742. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  29743. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  29744. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  29745. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  29746. // push each facet index in each block containing the vertex
  29747. options.facetPartitioning[block_idx_v1].push(index);
  29748. if (block_idx_v2 != block_idx_v1) {
  29749. options.facetPartitioning[block_idx_v2].push(index);
  29750. }
  29751. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  29752. options.facetPartitioning[block_idx_v3].push(index);
  29753. }
  29754. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  29755. options.facetPartitioning[block_idx_o].push(index);
  29756. }
  29757. }
  29758. // compute the normals anyway
  29759. normals[v1x] += faceNormalx; // accumulate all the normals per face
  29760. normals[v1y] += faceNormaly;
  29761. normals[v1z] += faceNormalz;
  29762. normals[v2x] += faceNormalx;
  29763. normals[v2y] += faceNormaly;
  29764. normals[v2z] += faceNormalz;
  29765. normals[v3x] += faceNormalx;
  29766. normals[v3y] += faceNormaly;
  29767. normals[v3z] += faceNormalz;
  29768. }
  29769. // last normalization of each normal
  29770. for (index = 0; index < normals.length / 3; index++) {
  29771. faceNormalx = normals[index * 3];
  29772. faceNormaly = normals[index * 3 + 1];
  29773. faceNormalz = normals[index * 3 + 2];
  29774. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29775. length = (length === 0) ? 1.0 : length;
  29776. faceNormalx /= length;
  29777. faceNormaly /= length;
  29778. faceNormalz /= length;
  29779. normals[index * 3] = faceNormalx;
  29780. normals[index * 3 + 1] = faceNormaly;
  29781. normals[index * 3 + 2] = faceNormalz;
  29782. }
  29783. };
  29784. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  29785. var li = indices.length;
  29786. var ln = normals.length;
  29787. var i;
  29788. var n;
  29789. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29790. switch (sideOrientation) {
  29791. case BABYLON.Mesh.FRONTSIDE:
  29792. // nothing changed
  29793. break;
  29794. case BABYLON.Mesh.BACKSIDE:
  29795. var tmp;
  29796. // indices
  29797. for (i = 0; i < li; i += 3) {
  29798. tmp = indices[i];
  29799. indices[i] = indices[i + 2];
  29800. indices[i + 2] = tmp;
  29801. }
  29802. // normals
  29803. for (n = 0; n < ln; n++) {
  29804. normals[n] = -normals[n];
  29805. }
  29806. break;
  29807. case BABYLON.Mesh.DOUBLESIDE:
  29808. // positions
  29809. var lp = positions.length;
  29810. var l = lp / 3;
  29811. for (var p = 0; p < lp; p++) {
  29812. positions[lp + p] = positions[p];
  29813. }
  29814. // indices
  29815. for (i = 0; i < li; i += 3) {
  29816. indices[i + li] = indices[i + 2] + l;
  29817. indices[i + 1 + li] = indices[i + 1] + l;
  29818. indices[i + 2 + li] = indices[i] + l;
  29819. }
  29820. // normals
  29821. for (n = 0; n < ln; n++) {
  29822. normals[ln + n] = -normals[n];
  29823. }
  29824. // uvs
  29825. var lu = uvs.length;
  29826. var u = 0;
  29827. for (u = 0; u < lu; u++) {
  29828. uvs[u + lu] = uvs[u];
  29829. }
  29830. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  29831. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  29832. u = 0;
  29833. for (i = 0; i < lu / 2; i++) {
  29834. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  29835. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  29836. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  29837. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  29838. u += 2;
  29839. }
  29840. break;
  29841. }
  29842. };
  29843. /**
  29844. * Creates a new VertexData from the imported parameters.
  29845. */
  29846. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29847. var vertexData = new VertexData();
  29848. // positions
  29849. var positions = parsedVertexData.positions;
  29850. if (positions) {
  29851. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29852. }
  29853. // normals
  29854. var normals = parsedVertexData.normals;
  29855. if (normals) {
  29856. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29857. }
  29858. // tangents
  29859. var tangents = parsedVertexData.tangents;
  29860. if (tangents) {
  29861. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  29862. }
  29863. // uvs
  29864. var uvs = parsedVertexData.uvs;
  29865. if (uvs) {
  29866. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29867. }
  29868. // uv2s
  29869. var uv2s = parsedVertexData.uv2s;
  29870. if (uv2s) {
  29871. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29872. }
  29873. // uv3s
  29874. var uv3s = parsedVertexData.uv3s;
  29875. if (uv3s) {
  29876. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29877. }
  29878. // uv4s
  29879. var uv4s = parsedVertexData.uv4s;
  29880. if (uv4s) {
  29881. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29882. }
  29883. // uv5s
  29884. var uv5s = parsedVertexData.uv5s;
  29885. if (uv5s) {
  29886. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29887. }
  29888. // uv6s
  29889. var uv6s = parsedVertexData.uv6s;
  29890. if (uv6s) {
  29891. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29892. }
  29893. // colors
  29894. var colors = parsedVertexData.colors;
  29895. if (colors) {
  29896. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29897. }
  29898. // matricesIndices
  29899. var matricesIndices = parsedVertexData.matricesIndices;
  29900. if (matricesIndices) {
  29901. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29902. }
  29903. // matricesWeights
  29904. var matricesWeights = parsedVertexData.matricesWeights;
  29905. if (matricesWeights) {
  29906. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29907. }
  29908. // indices
  29909. var indices = parsedVertexData.indices;
  29910. if (indices) {
  29911. vertexData.indices = indices;
  29912. }
  29913. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29914. };
  29915. return VertexData;
  29916. }());
  29917. BABYLON.VertexData = VertexData;
  29918. })(BABYLON || (BABYLON = {}));
  29919. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  29920. var BABYLON;
  29921. (function (BABYLON) {
  29922. var Geometry = /** @class */ (function () {
  29923. function Geometry(id, scene, vertexData, updatable, mesh) {
  29924. if (updatable === void 0) { updatable = false; }
  29925. if (mesh === void 0) { mesh = null; }
  29926. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29927. this._totalVertices = 0;
  29928. this._isDisposed = false;
  29929. this._indexBufferIsUpdatable = false;
  29930. this.id = id;
  29931. this._engine = scene.getEngine();
  29932. this._meshes = [];
  29933. this._scene = scene;
  29934. //Init vertex buffer cache
  29935. this._vertexBuffers = {};
  29936. this._indices = [];
  29937. this._updatable = updatable;
  29938. // vertexData
  29939. if (vertexData) {
  29940. this.setAllVerticesData(vertexData, updatable);
  29941. }
  29942. else {
  29943. this._totalVertices = 0;
  29944. this._indices = [];
  29945. }
  29946. if (this._engine.getCaps().vertexArrayObject) {
  29947. this._vertexArrayObjects = {};
  29948. }
  29949. // applyToMesh
  29950. if (mesh) {
  29951. if (mesh.getClassName() === "LinesMesh") {
  29952. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  29953. this.updateExtend();
  29954. }
  29955. this.applyToMesh(mesh);
  29956. mesh.computeWorldMatrix(true);
  29957. }
  29958. }
  29959. Object.defineProperty(Geometry.prototype, "boundingBias", {
  29960. /**
  29961. * 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
  29962. * @returns The Bias Vector
  29963. */
  29964. get: function () {
  29965. return this._boundingBias;
  29966. },
  29967. set: function (value) {
  29968. if (this._boundingBias && this._boundingBias.equals(value)) {
  29969. return;
  29970. }
  29971. this._boundingBias = value.clone();
  29972. this.updateBoundingInfo(true, null);
  29973. },
  29974. enumerable: true,
  29975. configurable: true
  29976. });
  29977. Geometry.CreateGeometryForMesh = function (mesh) {
  29978. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  29979. geometry.applyToMesh(mesh);
  29980. return geometry;
  29981. };
  29982. Object.defineProperty(Geometry.prototype, "extend", {
  29983. get: function () {
  29984. return this._extend;
  29985. },
  29986. enumerable: true,
  29987. configurable: true
  29988. });
  29989. Geometry.prototype.getScene = function () {
  29990. return this._scene;
  29991. };
  29992. Geometry.prototype.getEngine = function () {
  29993. return this._engine;
  29994. };
  29995. Geometry.prototype.isReady = function () {
  29996. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29997. };
  29998. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  29999. get: function () {
  30000. for (var index = 0; index < this._meshes.length; index++) {
  30001. if (!this._meshes[index].doNotSerialize) {
  30002. return false;
  30003. }
  30004. }
  30005. return true;
  30006. },
  30007. enumerable: true,
  30008. configurable: true
  30009. });
  30010. Geometry.prototype._rebuild = function () {
  30011. if (this._vertexArrayObjects) {
  30012. this._vertexArrayObjects = {};
  30013. }
  30014. // Index buffer
  30015. if (this._meshes.length !== 0 && this._indices) {
  30016. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30017. }
  30018. // Vertex buffers
  30019. for (var key in this._vertexBuffers) {
  30020. var vertexBuffer = this._vertexBuffers[key];
  30021. vertexBuffer._rebuild();
  30022. }
  30023. };
  30024. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30025. vertexData.applyToGeometry(this, updatable);
  30026. this.notifyUpdate();
  30027. };
  30028. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30029. if (updatable === void 0) { updatable = false; }
  30030. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30031. this.setVerticesBuffer(buffer);
  30032. };
  30033. Geometry.prototype.removeVerticesData = function (kind) {
  30034. if (this._vertexBuffers[kind]) {
  30035. this._vertexBuffers[kind].dispose();
  30036. delete this._vertexBuffers[kind];
  30037. }
  30038. };
  30039. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30040. var kind = buffer.getKind();
  30041. if (this._vertexBuffers[kind]) {
  30042. this._vertexBuffers[kind].dispose();
  30043. }
  30044. this._vertexBuffers[kind] = buffer;
  30045. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30046. var data = buffer.getData();
  30047. var stride = buffer.getStrideSize();
  30048. this._totalVertices = data.length / stride;
  30049. this.updateExtend(data, stride);
  30050. this._resetPointsArrayCache();
  30051. var meshes = this._meshes;
  30052. var numOfMeshes = meshes.length;
  30053. for (var index = 0; index < numOfMeshes; index++) {
  30054. var mesh = meshes[index];
  30055. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30056. mesh._createGlobalSubMesh(false);
  30057. mesh.computeWorldMatrix(true);
  30058. }
  30059. }
  30060. this.notifyUpdate(kind);
  30061. if (this._vertexArrayObjects) {
  30062. this._disposeVertexArrayObjects();
  30063. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30064. }
  30065. };
  30066. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30067. var vertexBuffer = this.getVertexBuffer(kind);
  30068. if (!vertexBuffer) {
  30069. return;
  30070. }
  30071. vertexBuffer.updateDirectly(data, offset);
  30072. this.notifyUpdate(kind);
  30073. };
  30074. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30075. if (updateExtends === void 0) { updateExtends = false; }
  30076. var vertexBuffer = this.getVertexBuffer(kind);
  30077. if (!vertexBuffer) {
  30078. return;
  30079. }
  30080. vertexBuffer.update(data);
  30081. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30082. var stride = vertexBuffer.getStrideSize();
  30083. this._totalVertices = data.length / stride;
  30084. this.updateBoundingInfo(updateExtends, data);
  30085. }
  30086. this.notifyUpdate(kind);
  30087. };
  30088. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30089. if (updateExtends) {
  30090. this.updateExtend(data);
  30091. }
  30092. var meshes = this._meshes;
  30093. var numOfMeshes = meshes.length;
  30094. this._resetPointsArrayCache();
  30095. for (var index = 0; index < numOfMeshes; index++) {
  30096. var mesh = meshes[index];
  30097. if (updateExtends) {
  30098. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30099. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30100. var subMesh = mesh.subMeshes[subIndex];
  30101. subMesh.refreshBoundingInfo();
  30102. }
  30103. }
  30104. }
  30105. };
  30106. Geometry.prototype._bind = function (effect, indexToBind) {
  30107. if (!effect) {
  30108. return;
  30109. }
  30110. if (indexToBind === undefined) {
  30111. indexToBind = this._indexBuffer;
  30112. }
  30113. var vbs = this.getVertexBuffers();
  30114. if (!vbs) {
  30115. return;
  30116. }
  30117. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30118. this._engine.bindBuffers(vbs, indexToBind, effect);
  30119. return;
  30120. }
  30121. // Using VAO
  30122. if (!this._vertexArrayObjects[effect.key]) {
  30123. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30124. }
  30125. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30126. };
  30127. Geometry.prototype.getTotalVertices = function () {
  30128. if (!this.isReady()) {
  30129. return 0;
  30130. }
  30131. return this._totalVertices;
  30132. };
  30133. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30134. var vertexBuffer = this.getVertexBuffer(kind);
  30135. if (!vertexBuffer) {
  30136. return null;
  30137. }
  30138. var orig = vertexBuffer.getData();
  30139. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30140. return orig;
  30141. }
  30142. else {
  30143. var len = orig.length;
  30144. var copy = [];
  30145. for (var i = 0; i < len; i++) {
  30146. copy.push(orig[i]);
  30147. }
  30148. return copy;
  30149. }
  30150. };
  30151. /**
  30152. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30153. * Possible `kind` values :
  30154. * - BABYLON.VertexBuffer.PositionKind
  30155. * - BABYLON.VertexBuffer.UVKind
  30156. * - BABYLON.VertexBuffer.UV2Kind
  30157. * - BABYLON.VertexBuffer.UV3Kind
  30158. * - BABYLON.VertexBuffer.UV4Kind
  30159. * - BABYLON.VertexBuffer.UV5Kind
  30160. * - BABYLON.VertexBuffer.UV6Kind
  30161. * - BABYLON.VertexBuffer.ColorKind
  30162. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30163. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30164. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30165. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30166. */
  30167. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30168. var vb = this._vertexBuffers[kind];
  30169. if (!vb) {
  30170. return false;
  30171. }
  30172. return vb.isUpdatable();
  30173. };
  30174. Geometry.prototype.getVertexBuffer = function (kind) {
  30175. if (!this.isReady()) {
  30176. return null;
  30177. }
  30178. return this._vertexBuffers[kind];
  30179. };
  30180. Geometry.prototype.getVertexBuffers = function () {
  30181. if (!this.isReady()) {
  30182. return null;
  30183. }
  30184. return this._vertexBuffers;
  30185. };
  30186. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30187. if (!this._vertexBuffers) {
  30188. if (this._delayInfo) {
  30189. return this._delayInfo.indexOf(kind) !== -1;
  30190. }
  30191. return false;
  30192. }
  30193. return this._vertexBuffers[kind] !== undefined;
  30194. };
  30195. Geometry.prototype.getVerticesDataKinds = function () {
  30196. var result = [];
  30197. var kind;
  30198. if (!this._vertexBuffers && this._delayInfo) {
  30199. for (kind in this._delayInfo) {
  30200. result.push(kind);
  30201. }
  30202. }
  30203. else {
  30204. for (kind in this._vertexBuffers) {
  30205. result.push(kind);
  30206. }
  30207. }
  30208. return result;
  30209. };
  30210. Geometry.prototype.updateIndices = function (indices, offset) {
  30211. if (!this._indexBuffer) {
  30212. return;
  30213. }
  30214. if (!this._indexBufferIsUpdatable) {
  30215. this.setIndices(indices, null, true);
  30216. }
  30217. else {
  30218. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30219. }
  30220. };
  30221. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30222. if (totalVertices === void 0) { totalVertices = null; }
  30223. if (updatable === void 0) { updatable = false; }
  30224. if (this._indexBuffer) {
  30225. this._engine._releaseBuffer(this._indexBuffer);
  30226. }
  30227. this._disposeVertexArrayObjects();
  30228. this._indices = indices;
  30229. this._indexBufferIsUpdatable = updatable;
  30230. if (this._meshes.length !== 0 && this._indices) {
  30231. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30232. }
  30233. if (totalVertices != undefined) {
  30234. this._totalVertices = totalVertices;
  30235. }
  30236. var meshes = this._meshes;
  30237. var numOfMeshes = meshes.length;
  30238. for (var index = 0; index < numOfMeshes; index++) {
  30239. meshes[index]._createGlobalSubMesh(true);
  30240. }
  30241. this.notifyUpdate();
  30242. };
  30243. Geometry.prototype.getTotalIndices = function () {
  30244. if (!this.isReady()) {
  30245. return 0;
  30246. }
  30247. return this._indices.length;
  30248. };
  30249. Geometry.prototype.getIndices = function (copyWhenShared) {
  30250. if (!this.isReady()) {
  30251. return null;
  30252. }
  30253. var orig = this._indices;
  30254. if (!copyWhenShared || this._meshes.length === 1) {
  30255. return orig;
  30256. }
  30257. else {
  30258. var len = orig.length;
  30259. var copy = [];
  30260. for (var i = 0; i < len; i++) {
  30261. copy.push(orig[i]);
  30262. }
  30263. return copy;
  30264. }
  30265. };
  30266. Geometry.prototype.getIndexBuffer = function () {
  30267. if (!this.isReady()) {
  30268. return null;
  30269. }
  30270. return this._indexBuffer;
  30271. };
  30272. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30273. if (effect === void 0) { effect = null; }
  30274. if (!effect || !this._vertexArrayObjects) {
  30275. return;
  30276. }
  30277. if (this._vertexArrayObjects[effect.key]) {
  30278. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30279. delete this._vertexArrayObjects[effect.key];
  30280. }
  30281. };
  30282. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30283. var meshes = this._meshes;
  30284. var index = meshes.indexOf(mesh);
  30285. if (index === -1) {
  30286. return;
  30287. }
  30288. meshes.splice(index, 1);
  30289. mesh._geometry = null;
  30290. if (meshes.length === 0 && shouldDispose) {
  30291. this.dispose();
  30292. }
  30293. };
  30294. Geometry.prototype.applyToMesh = function (mesh) {
  30295. if (mesh._geometry === this) {
  30296. return;
  30297. }
  30298. var previousGeometry = mesh._geometry;
  30299. if (previousGeometry) {
  30300. previousGeometry.releaseForMesh(mesh);
  30301. }
  30302. var meshes = this._meshes;
  30303. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30304. mesh._geometry = this;
  30305. this._scene.pushGeometry(this);
  30306. meshes.push(mesh);
  30307. if (this.isReady()) {
  30308. this._applyToMesh(mesh);
  30309. }
  30310. else {
  30311. mesh._boundingInfo = this._boundingInfo;
  30312. }
  30313. };
  30314. Geometry.prototype.updateExtend = function (data, stride) {
  30315. if (data === void 0) { data = null; }
  30316. if (!data) {
  30317. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30318. }
  30319. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30320. };
  30321. Geometry.prototype._applyToMesh = function (mesh) {
  30322. var numOfMeshes = this._meshes.length;
  30323. // vertexBuffers
  30324. for (var kind in this._vertexBuffers) {
  30325. if (numOfMeshes === 1) {
  30326. this._vertexBuffers[kind].create();
  30327. }
  30328. var buffer = this._vertexBuffers[kind].getBuffer();
  30329. if (buffer)
  30330. buffer.references = numOfMeshes;
  30331. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30332. if (!this._extend) {
  30333. this.updateExtend(this._vertexBuffers[kind].getData());
  30334. }
  30335. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30336. mesh._createGlobalSubMesh(false);
  30337. //bounding info was just created again, world matrix should be applied again.
  30338. mesh._updateBoundingInfo();
  30339. }
  30340. }
  30341. // indexBuffer
  30342. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30343. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30344. }
  30345. if (this._indexBuffer) {
  30346. this._indexBuffer.references = numOfMeshes;
  30347. }
  30348. };
  30349. Geometry.prototype.notifyUpdate = function (kind) {
  30350. if (this.onGeometryUpdated) {
  30351. this.onGeometryUpdated(this, kind);
  30352. }
  30353. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30354. var mesh = _a[_i];
  30355. mesh._markSubMeshesAsAttributesDirty();
  30356. }
  30357. };
  30358. Geometry.prototype.load = function (scene, onLoaded) {
  30359. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30360. return;
  30361. }
  30362. if (this.isReady()) {
  30363. if (onLoaded) {
  30364. onLoaded();
  30365. }
  30366. return;
  30367. }
  30368. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30369. this._queueLoad(scene, onLoaded);
  30370. };
  30371. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30372. var _this = this;
  30373. if (!this.delayLoadingFile) {
  30374. return;
  30375. }
  30376. scene._addPendingData(this);
  30377. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30378. if (!_this._delayLoadingFunction) {
  30379. return;
  30380. }
  30381. _this._delayLoadingFunction(JSON.parse(data), _this);
  30382. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30383. _this._delayInfo = [];
  30384. scene._removePendingData(_this);
  30385. var meshes = _this._meshes;
  30386. var numOfMeshes = meshes.length;
  30387. for (var index = 0; index < numOfMeshes; index++) {
  30388. _this._applyToMesh(meshes[index]);
  30389. }
  30390. if (onLoaded) {
  30391. onLoaded();
  30392. }
  30393. }, function () { }, scene.database);
  30394. };
  30395. /**
  30396. * Invert the geometry to move from a right handed system to a left handed one.
  30397. */
  30398. Geometry.prototype.toLeftHanded = function () {
  30399. // Flip faces
  30400. var tIndices = this.getIndices(false);
  30401. if (tIndices != null && tIndices.length > 0) {
  30402. for (var i = 0; i < tIndices.length; i += 3) {
  30403. var tTemp = tIndices[i + 0];
  30404. tIndices[i + 0] = tIndices[i + 2];
  30405. tIndices[i + 2] = tTemp;
  30406. }
  30407. this.setIndices(tIndices);
  30408. }
  30409. // Negate position.z
  30410. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30411. if (tPositions != null && tPositions.length > 0) {
  30412. for (var i = 0; i < tPositions.length; i += 3) {
  30413. tPositions[i + 2] = -tPositions[i + 2];
  30414. }
  30415. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30416. }
  30417. // Negate normal.z
  30418. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30419. if (tNormals != null && tNormals.length > 0) {
  30420. for (var i = 0; i < tNormals.length; i += 3) {
  30421. tNormals[i + 2] = -tNormals[i + 2];
  30422. }
  30423. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30424. }
  30425. };
  30426. // Cache
  30427. Geometry.prototype._resetPointsArrayCache = function () {
  30428. this._positions = null;
  30429. };
  30430. Geometry.prototype._generatePointsArray = function () {
  30431. if (this._positions)
  30432. return true;
  30433. this._positions = [];
  30434. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30435. if (!data) {
  30436. return false;
  30437. }
  30438. for (var index = 0; index < data.length; index += 3) {
  30439. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30440. }
  30441. return true;
  30442. };
  30443. Geometry.prototype.isDisposed = function () {
  30444. return this._isDisposed;
  30445. };
  30446. Geometry.prototype._disposeVertexArrayObjects = function () {
  30447. if (this._vertexArrayObjects) {
  30448. for (var kind in this._vertexArrayObjects) {
  30449. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30450. }
  30451. this._vertexArrayObjects = {};
  30452. }
  30453. };
  30454. Geometry.prototype.dispose = function () {
  30455. var meshes = this._meshes;
  30456. var numOfMeshes = meshes.length;
  30457. var index;
  30458. for (index = 0; index < numOfMeshes; index++) {
  30459. this.releaseForMesh(meshes[index]);
  30460. }
  30461. this._meshes = [];
  30462. this._disposeVertexArrayObjects();
  30463. for (var kind in this._vertexBuffers) {
  30464. this._vertexBuffers[kind].dispose();
  30465. }
  30466. this._vertexBuffers = {};
  30467. this._totalVertices = 0;
  30468. if (this._indexBuffer) {
  30469. this._engine._releaseBuffer(this._indexBuffer);
  30470. }
  30471. this._indexBuffer = null;
  30472. this._indices = [];
  30473. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30474. this.delayLoadingFile = null;
  30475. this._delayLoadingFunction = null;
  30476. this._delayInfo = [];
  30477. this._boundingInfo = null;
  30478. this._scene.removeGeometry(this);
  30479. this._isDisposed = true;
  30480. };
  30481. Geometry.prototype.copy = function (id) {
  30482. var vertexData = new BABYLON.VertexData();
  30483. vertexData.indices = [];
  30484. var indices = this.getIndices();
  30485. if (indices) {
  30486. for (var index = 0; index < indices.length; index++) {
  30487. vertexData.indices.push(indices[index]);
  30488. }
  30489. }
  30490. var updatable = false;
  30491. var stopChecking = false;
  30492. var kind;
  30493. for (kind in this._vertexBuffers) {
  30494. // using slice() to make a copy of the array and not just reference it
  30495. var data = this.getVerticesData(kind);
  30496. if (data instanceof Float32Array) {
  30497. vertexData.set(new Float32Array(data), kind);
  30498. }
  30499. else {
  30500. vertexData.set(data.slice(0), kind);
  30501. }
  30502. if (!stopChecking) {
  30503. var vb = this.getVertexBuffer(kind);
  30504. if (vb) {
  30505. updatable = vb.isUpdatable();
  30506. stopChecking = !updatable;
  30507. }
  30508. }
  30509. }
  30510. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30511. geometry.delayLoadState = this.delayLoadState;
  30512. geometry.delayLoadingFile = this.delayLoadingFile;
  30513. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30514. for (kind in this._delayInfo) {
  30515. geometry._delayInfo = geometry._delayInfo || [];
  30516. geometry._delayInfo.push(kind);
  30517. }
  30518. // Bounding info
  30519. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30520. return geometry;
  30521. };
  30522. Geometry.prototype.serialize = function () {
  30523. var serializationObject = {};
  30524. serializationObject.id = this.id;
  30525. serializationObject.updatable = this._updatable;
  30526. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30527. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30528. }
  30529. return serializationObject;
  30530. };
  30531. Geometry.prototype.toNumberArray = function (origin) {
  30532. if (Array.isArray(origin)) {
  30533. return origin;
  30534. }
  30535. else {
  30536. return Array.prototype.slice.call(origin);
  30537. }
  30538. };
  30539. Geometry.prototype.serializeVerticeData = function () {
  30540. var serializationObject = this.serialize();
  30541. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30542. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30543. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30544. serializationObject.positions._updatable = true;
  30545. }
  30546. }
  30547. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30548. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30549. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30550. serializationObject.normals._updatable = true;
  30551. }
  30552. }
  30553. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30554. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30555. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30556. serializationObject.uvs._updatable = true;
  30557. }
  30558. }
  30559. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30560. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30561. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30562. serializationObject.uv2s._updatable = true;
  30563. }
  30564. }
  30565. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30566. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30567. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30568. serializationObject.uv3s._updatable = true;
  30569. }
  30570. }
  30571. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30572. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30573. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30574. serializationObject.uv4s._updatable = true;
  30575. }
  30576. }
  30577. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30578. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30579. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30580. serializationObject.uv5s._updatable = true;
  30581. }
  30582. }
  30583. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30584. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30585. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30586. serializationObject.uv6s._updatable = true;
  30587. }
  30588. }
  30589. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30590. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30591. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30592. serializationObject.colors._updatable = true;
  30593. }
  30594. }
  30595. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30596. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30597. serializationObject.matricesIndices._isExpanded = true;
  30598. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30599. serializationObject.matricesIndices._updatable = true;
  30600. }
  30601. }
  30602. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30603. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30604. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30605. serializationObject.matricesWeights._updatable = true;
  30606. }
  30607. }
  30608. serializationObject.indices = this.toNumberArray(this.getIndices());
  30609. return serializationObject;
  30610. };
  30611. // Statics
  30612. Geometry.ExtractFromMesh = function (mesh, id) {
  30613. var geometry = mesh._geometry;
  30614. if (!geometry) {
  30615. return null;
  30616. }
  30617. return geometry.copy(id);
  30618. };
  30619. /**
  30620. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30621. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30622. * Be aware Math.random() could cause collisions, but:
  30623. * "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"
  30624. */
  30625. Geometry.RandomId = function () {
  30626. return BABYLON.Tools.RandomId();
  30627. };
  30628. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30629. var scene = mesh.getScene();
  30630. // Geometry
  30631. var geometryId = parsedGeometry.geometryId;
  30632. if (geometryId) {
  30633. var geometry = scene.getGeometryByID(geometryId);
  30634. if (geometry) {
  30635. geometry.applyToMesh(mesh);
  30636. }
  30637. }
  30638. else if (parsedGeometry instanceof ArrayBuffer) {
  30639. var binaryInfo = mesh._binaryInfo;
  30640. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30641. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30642. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30643. }
  30644. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30645. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30646. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30647. }
  30648. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30649. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30650. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30651. }
  30652. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30653. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30654. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30655. }
  30656. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30657. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30658. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30659. }
  30660. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30661. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30662. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30663. }
  30664. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30665. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30666. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30667. }
  30668. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30669. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30670. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30671. }
  30672. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30673. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30674. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30675. }
  30676. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30677. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30678. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30679. }
  30680. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30681. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30682. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  30683. }
  30684. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  30685. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  30686. mesh.setIndices(indicesData, null);
  30687. }
  30688. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  30689. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  30690. mesh.subMeshes = [];
  30691. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  30692. var materialIndex = subMeshesData[(i * 5) + 0];
  30693. var verticesStart = subMeshesData[(i * 5) + 1];
  30694. var verticesCount = subMeshesData[(i * 5) + 2];
  30695. var indexStart = subMeshesData[(i * 5) + 3];
  30696. var indexCount = subMeshesData[(i * 5) + 4];
  30697. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  30698. }
  30699. }
  30700. }
  30701. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  30702. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  30703. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  30704. if (parsedGeometry.uvs) {
  30705. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  30706. }
  30707. if (parsedGeometry.uvs2) {
  30708. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  30709. }
  30710. if (parsedGeometry.uvs3) {
  30711. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  30712. }
  30713. if (parsedGeometry.uvs4) {
  30714. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  30715. }
  30716. if (parsedGeometry.uvs5) {
  30717. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  30718. }
  30719. if (parsedGeometry.uvs6) {
  30720. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  30721. }
  30722. if (parsedGeometry.colors) {
  30723. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  30724. }
  30725. if (parsedGeometry.matricesIndices) {
  30726. if (!parsedGeometry.matricesIndices._isExpanded) {
  30727. var floatIndices = [];
  30728. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  30729. var matricesIndex = parsedGeometry.matricesIndices[i];
  30730. floatIndices.push(matricesIndex & 0x000000FF);
  30731. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30732. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30733. floatIndices.push(matricesIndex >> 24);
  30734. }
  30735. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  30736. }
  30737. else {
  30738. delete parsedGeometry.matricesIndices._isExpanded;
  30739. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  30740. }
  30741. }
  30742. if (parsedGeometry.matricesIndicesExtra) {
  30743. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  30744. var floatIndices = [];
  30745. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  30746. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  30747. floatIndices.push(matricesIndex & 0x000000FF);
  30748. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30749. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30750. floatIndices.push(matricesIndex >> 24);
  30751. }
  30752. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  30753. }
  30754. else {
  30755. delete parsedGeometry.matricesIndices._isExpanded;
  30756. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  30757. }
  30758. }
  30759. if (parsedGeometry.matricesWeights) {
  30760. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  30761. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  30762. }
  30763. if (parsedGeometry.matricesWeightsExtra) {
  30764. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  30765. }
  30766. mesh.setIndices(parsedGeometry.indices, null);
  30767. }
  30768. // SubMeshes
  30769. if (parsedGeometry.subMeshes) {
  30770. mesh.subMeshes = [];
  30771. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30772. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30773. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30774. }
  30775. }
  30776. // Flat shading
  30777. if (mesh._shouldGenerateFlatShading) {
  30778. mesh.convertToFlatShadedMesh();
  30779. delete mesh._shouldGenerateFlatShading;
  30780. }
  30781. // Update
  30782. mesh.computeWorldMatrix(true);
  30783. // Octree
  30784. if (scene['_selectionOctree']) {
  30785. scene['_selectionOctree'].addMesh(mesh);
  30786. }
  30787. };
  30788. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  30789. var epsilon = 1e-3;
  30790. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  30791. return;
  30792. }
  30793. var noInfluenceBoneIndex = 0.0;
  30794. if (parsedGeometry.skeletonId > -1) {
  30795. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  30796. if (!skeleton) {
  30797. return;
  30798. }
  30799. noInfluenceBoneIndex = skeleton.bones.length;
  30800. }
  30801. else {
  30802. return;
  30803. }
  30804. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30805. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  30806. var matricesWeights = parsedGeometry.matricesWeights;
  30807. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  30808. var influencers = parsedGeometry.numBoneInfluencer;
  30809. var size = matricesWeights.length;
  30810. for (var i = 0; i < size; i += 4) {
  30811. var weight = 0.0;
  30812. var firstZeroWeight = -1;
  30813. for (var j = 0; j < 4; j++) {
  30814. var w = matricesWeights[i + j];
  30815. weight += w;
  30816. if (w < epsilon && firstZeroWeight < 0) {
  30817. firstZeroWeight = j;
  30818. }
  30819. }
  30820. if (matricesWeightsExtra) {
  30821. for (var j = 0; j < 4; j++) {
  30822. var w = matricesWeightsExtra[i + j];
  30823. weight += w;
  30824. if (w < epsilon && firstZeroWeight < 0) {
  30825. firstZeroWeight = j + 4;
  30826. }
  30827. }
  30828. }
  30829. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  30830. firstZeroWeight = influencers - 1;
  30831. }
  30832. if (weight > epsilon) {
  30833. var mweight = 1.0 / weight;
  30834. for (var j = 0; j < 4; j++) {
  30835. matricesWeights[i + j] *= mweight;
  30836. }
  30837. if (matricesWeightsExtra) {
  30838. for (var j = 0; j < 4; j++) {
  30839. matricesWeightsExtra[i + j] *= mweight;
  30840. }
  30841. }
  30842. }
  30843. else {
  30844. if (firstZeroWeight >= 4) {
  30845. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  30846. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  30847. }
  30848. else {
  30849. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  30850. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  30851. }
  30852. }
  30853. }
  30854. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  30855. if (parsedGeometry.matricesWeightsExtra) {
  30856. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  30857. }
  30858. };
  30859. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  30860. if (scene.getGeometryByID(parsedVertexData.id)) {
  30861. return null; // null since geometry could be something else than a box...
  30862. }
  30863. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  30864. if (BABYLON.Tags) {
  30865. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  30866. }
  30867. if (parsedVertexData.delayLoadingFile) {
  30868. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30869. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  30870. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  30871. geometry._delayInfo = [];
  30872. if (parsedVertexData.hasUVs) {
  30873. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30874. }
  30875. if (parsedVertexData.hasUVs2) {
  30876. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30877. }
  30878. if (parsedVertexData.hasUVs3) {
  30879. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30880. }
  30881. if (parsedVertexData.hasUVs4) {
  30882. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30883. }
  30884. if (parsedVertexData.hasUVs5) {
  30885. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30886. }
  30887. if (parsedVertexData.hasUVs6) {
  30888. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30889. }
  30890. if (parsedVertexData.hasColors) {
  30891. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30892. }
  30893. if (parsedVertexData.hasMatricesIndices) {
  30894. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30895. }
  30896. if (parsedVertexData.hasMatricesWeights) {
  30897. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30898. }
  30899. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  30900. }
  30901. else {
  30902. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  30903. }
  30904. scene.pushGeometry(geometry, true);
  30905. return geometry;
  30906. };
  30907. return Geometry;
  30908. }());
  30909. BABYLON.Geometry = Geometry;
  30910. /////// Primitives //////////////////////////////////////////////
  30911. (function (Geometry) {
  30912. var Primitives;
  30913. (function (Primitives) {
  30914. /// Abstract class
  30915. var _Primitive = /** @class */ (function (_super) {
  30916. __extends(_Primitive, _super);
  30917. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  30918. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  30919. if (mesh === void 0) { mesh = null; }
  30920. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  30921. _this._canBeRegenerated = _canBeRegenerated;
  30922. _this._beingRegenerated = true;
  30923. _this.regenerate();
  30924. _this._beingRegenerated = false;
  30925. return _this;
  30926. }
  30927. _Primitive.prototype.canBeRegenerated = function () {
  30928. return this._canBeRegenerated;
  30929. };
  30930. _Primitive.prototype.regenerate = function () {
  30931. if (!this._canBeRegenerated) {
  30932. return;
  30933. }
  30934. this._beingRegenerated = true;
  30935. this.setAllVerticesData(this._regenerateVertexData(), false);
  30936. this._beingRegenerated = false;
  30937. };
  30938. _Primitive.prototype.asNewGeometry = function (id) {
  30939. return _super.prototype.copy.call(this, id);
  30940. };
  30941. // overrides
  30942. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  30943. if (!this._beingRegenerated) {
  30944. return;
  30945. }
  30946. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  30947. };
  30948. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  30949. if (!this._beingRegenerated) {
  30950. return;
  30951. }
  30952. _super.prototype.setVerticesData.call(this, kind, data, false);
  30953. };
  30954. // to override
  30955. // protected
  30956. _Primitive.prototype._regenerateVertexData = function () {
  30957. throw new Error("Abstract method");
  30958. };
  30959. _Primitive.prototype.copy = function (id) {
  30960. throw new Error("Must be overriden in sub-classes.");
  30961. };
  30962. _Primitive.prototype.serialize = function () {
  30963. var serializationObject = _super.prototype.serialize.call(this);
  30964. serializationObject.canBeRegenerated = this.canBeRegenerated();
  30965. return serializationObject;
  30966. };
  30967. return _Primitive;
  30968. }(Geometry));
  30969. Primitives._Primitive = _Primitive;
  30970. var Ribbon = /** @class */ (function (_super) {
  30971. __extends(Ribbon, _super);
  30972. // Members
  30973. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  30974. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30975. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30976. _this.pathArray = pathArray;
  30977. _this.closeArray = closeArray;
  30978. _this.closePath = closePath;
  30979. _this.offset = offset;
  30980. _this.side = side;
  30981. return _this;
  30982. }
  30983. Ribbon.prototype._regenerateVertexData = function () {
  30984. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  30985. };
  30986. Ribbon.prototype.copy = function (id) {
  30987. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  30988. };
  30989. return Ribbon;
  30990. }(_Primitive));
  30991. Primitives.Ribbon = Ribbon;
  30992. var Box = /** @class */ (function (_super) {
  30993. __extends(Box, _super);
  30994. // Members
  30995. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  30996. if (mesh === void 0) { mesh = null; }
  30997. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30998. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30999. _this.size = size;
  31000. _this.side = side;
  31001. return _this;
  31002. }
  31003. Box.prototype._regenerateVertexData = function () {
  31004. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31005. };
  31006. Box.prototype.copy = function (id) {
  31007. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31008. };
  31009. Box.prototype.serialize = function () {
  31010. var serializationObject = _super.prototype.serialize.call(this);
  31011. serializationObject.size = this.size;
  31012. return serializationObject;
  31013. };
  31014. Box.Parse = function (parsedBox, scene) {
  31015. if (scene.getGeometryByID(parsedBox.id)) {
  31016. return null; // null since geometry could be something else than a box...
  31017. }
  31018. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31019. if (BABYLON.Tags) {
  31020. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31021. }
  31022. scene.pushGeometry(box, true);
  31023. return box;
  31024. };
  31025. return Box;
  31026. }(_Primitive));
  31027. Primitives.Box = Box;
  31028. var Sphere = /** @class */ (function (_super) {
  31029. __extends(Sphere, _super);
  31030. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31031. if (mesh === void 0) { mesh = null; }
  31032. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31033. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31034. _this.segments = segments;
  31035. _this.diameter = diameter;
  31036. _this.side = side;
  31037. return _this;
  31038. }
  31039. Sphere.prototype._regenerateVertexData = function () {
  31040. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31041. };
  31042. Sphere.prototype.copy = function (id) {
  31043. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31044. };
  31045. Sphere.prototype.serialize = function () {
  31046. var serializationObject = _super.prototype.serialize.call(this);
  31047. serializationObject.segments = this.segments;
  31048. serializationObject.diameter = this.diameter;
  31049. return serializationObject;
  31050. };
  31051. Sphere.Parse = function (parsedSphere, scene) {
  31052. if (scene.getGeometryByID(parsedSphere.id)) {
  31053. return null; // null since geometry could be something else than a sphere...
  31054. }
  31055. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31056. if (BABYLON.Tags) {
  31057. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31058. }
  31059. scene.pushGeometry(sphere, true);
  31060. return sphere;
  31061. };
  31062. return Sphere;
  31063. }(_Primitive));
  31064. Primitives.Sphere = Sphere;
  31065. var Disc = /** @class */ (function (_super) {
  31066. __extends(Disc, _super);
  31067. // Members
  31068. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31069. if (mesh === void 0) { mesh = null; }
  31070. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31071. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31072. _this.radius = radius;
  31073. _this.tessellation = tessellation;
  31074. _this.side = side;
  31075. return _this;
  31076. }
  31077. Disc.prototype._regenerateVertexData = function () {
  31078. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31079. };
  31080. Disc.prototype.copy = function (id) {
  31081. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31082. };
  31083. return Disc;
  31084. }(_Primitive));
  31085. Primitives.Disc = Disc;
  31086. var Cylinder = /** @class */ (function (_super) {
  31087. __extends(Cylinder, _super);
  31088. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31089. if (subdivisions === void 0) { subdivisions = 1; }
  31090. if (mesh === void 0) { mesh = null; }
  31091. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31092. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31093. _this.height = height;
  31094. _this.diameterTop = diameterTop;
  31095. _this.diameterBottom = diameterBottom;
  31096. _this.tessellation = tessellation;
  31097. _this.subdivisions = subdivisions;
  31098. _this.side = side;
  31099. return _this;
  31100. }
  31101. Cylinder.prototype._regenerateVertexData = function () {
  31102. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31103. };
  31104. Cylinder.prototype.copy = function (id) {
  31105. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31106. };
  31107. Cylinder.prototype.serialize = function () {
  31108. var serializationObject = _super.prototype.serialize.call(this);
  31109. serializationObject.height = this.height;
  31110. serializationObject.diameterTop = this.diameterTop;
  31111. serializationObject.diameterBottom = this.diameterBottom;
  31112. serializationObject.tessellation = this.tessellation;
  31113. return serializationObject;
  31114. };
  31115. Cylinder.Parse = function (parsedCylinder, scene) {
  31116. if (scene.getGeometryByID(parsedCylinder.id)) {
  31117. return null; // null since geometry could be something else than a cylinder...
  31118. }
  31119. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31120. if (BABYLON.Tags) {
  31121. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31122. }
  31123. scene.pushGeometry(cylinder, true);
  31124. return cylinder;
  31125. };
  31126. return Cylinder;
  31127. }(_Primitive));
  31128. Primitives.Cylinder = Cylinder;
  31129. var Torus = /** @class */ (function (_super) {
  31130. __extends(Torus, _super);
  31131. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31132. if (mesh === void 0) { mesh = null; }
  31133. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31134. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31135. _this.diameter = diameter;
  31136. _this.thickness = thickness;
  31137. _this.tessellation = tessellation;
  31138. _this.side = side;
  31139. return _this;
  31140. }
  31141. Torus.prototype._regenerateVertexData = function () {
  31142. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31143. };
  31144. Torus.prototype.copy = function (id) {
  31145. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31146. };
  31147. Torus.prototype.serialize = function () {
  31148. var serializationObject = _super.prototype.serialize.call(this);
  31149. serializationObject.diameter = this.diameter;
  31150. serializationObject.thickness = this.thickness;
  31151. serializationObject.tessellation = this.tessellation;
  31152. return serializationObject;
  31153. };
  31154. Torus.Parse = function (parsedTorus, scene) {
  31155. if (scene.getGeometryByID(parsedTorus.id)) {
  31156. return null; // null since geometry could be something else than a torus...
  31157. }
  31158. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31159. if (BABYLON.Tags) {
  31160. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31161. }
  31162. scene.pushGeometry(torus, true);
  31163. return torus;
  31164. };
  31165. return Torus;
  31166. }(_Primitive));
  31167. Primitives.Torus = Torus;
  31168. var Ground = /** @class */ (function (_super) {
  31169. __extends(Ground, _super);
  31170. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31171. if (mesh === void 0) { mesh = null; }
  31172. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31173. _this.width = width;
  31174. _this.height = height;
  31175. _this.subdivisions = subdivisions;
  31176. return _this;
  31177. }
  31178. Ground.prototype._regenerateVertexData = function () {
  31179. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31180. };
  31181. Ground.prototype.copy = function (id) {
  31182. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31183. };
  31184. Ground.prototype.serialize = function () {
  31185. var serializationObject = _super.prototype.serialize.call(this);
  31186. serializationObject.width = this.width;
  31187. serializationObject.height = this.height;
  31188. serializationObject.subdivisions = this.subdivisions;
  31189. return serializationObject;
  31190. };
  31191. Ground.Parse = function (parsedGround, scene) {
  31192. if (scene.getGeometryByID(parsedGround.id)) {
  31193. return null; // null since geometry could be something else than a ground...
  31194. }
  31195. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31196. if (BABYLON.Tags) {
  31197. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31198. }
  31199. scene.pushGeometry(ground, true);
  31200. return ground;
  31201. };
  31202. return Ground;
  31203. }(_Primitive));
  31204. Primitives.Ground = Ground;
  31205. var TiledGround = /** @class */ (function (_super) {
  31206. __extends(TiledGround, _super);
  31207. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31208. if (mesh === void 0) { mesh = null; }
  31209. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31210. _this.xmin = xmin;
  31211. _this.zmin = zmin;
  31212. _this.xmax = xmax;
  31213. _this.zmax = zmax;
  31214. _this.subdivisions = subdivisions;
  31215. _this.precision = precision;
  31216. return _this;
  31217. }
  31218. TiledGround.prototype._regenerateVertexData = function () {
  31219. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31220. };
  31221. TiledGround.prototype.copy = function (id) {
  31222. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31223. };
  31224. return TiledGround;
  31225. }(_Primitive));
  31226. Primitives.TiledGround = TiledGround;
  31227. var Plane = /** @class */ (function (_super) {
  31228. __extends(Plane, _super);
  31229. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31230. if (mesh === void 0) { mesh = null; }
  31231. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31232. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31233. _this.size = size;
  31234. _this.side = side;
  31235. return _this;
  31236. }
  31237. Plane.prototype._regenerateVertexData = function () {
  31238. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31239. };
  31240. Plane.prototype.copy = function (id) {
  31241. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31242. };
  31243. Plane.prototype.serialize = function () {
  31244. var serializationObject = _super.prototype.serialize.call(this);
  31245. serializationObject.size = this.size;
  31246. return serializationObject;
  31247. };
  31248. Plane.Parse = function (parsedPlane, scene) {
  31249. if (scene.getGeometryByID(parsedPlane.id)) {
  31250. return null; // null since geometry could be something else than a ground...
  31251. }
  31252. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31253. if (BABYLON.Tags) {
  31254. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31255. }
  31256. scene.pushGeometry(plane, true);
  31257. return plane;
  31258. };
  31259. return Plane;
  31260. }(_Primitive));
  31261. Primitives.Plane = Plane;
  31262. var TorusKnot = /** @class */ (function (_super) {
  31263. __extends(TorusKnot, _super);
  31264. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31265. if (mesh === void 0) { mesh = null; }
  31266. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31267. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31268. _this.radius = radius;
  31269. _this.tube = tube;
  31270. _this.radialSegments = radialSegments;
  31271. _this.tubularSegments = tubularSegments;
  31272. _this.p = p;
  31273. _this.q = q;
  31274. _this.side = side;
  31275. return _this;
  31276. }
  31277. TorusKnot.prototype._regenerateVertexData = function () {
  31278. 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 });
  31279. };
  31280. TorusKnot.prototype.copy = function (id) {
  31281. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31282. };
  31283. TorusKnot.prototype.serialize = function () {
  31284. var serializationObject = _super.prototype.serialize.call(this);
  31285. serializationObject.radius = this.radius;
  31286. serializationObject.tube = this.tube;
  31287. serializationObject.radialSegments = this.radialSegments;
  31288. serializationObject.tubularSegments = this.tubularSegments;
  31289. serializationObject.p = this.p;
  31290. serializationObject.q = this.q;
  31291. return serializationObject;
  31292. };
  31293. ;
  31294. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31295. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31296. return null; // null since geometry could be something else than a ground...
  31297. }
  31298. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31299. if (BABYLON.Tags) {
  31300. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31301. }
  31302. scene.pushGeometry(torusKnot, true);
  31303. return torusKnot;
  31304. };
  31305. return TorusKnot;
  31306. }(_Primitive));
  31307. Primitives.TorusKnot = TorusKnot;
  31308. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31309. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31310. })(BABYLON || (BABYLON = {}));
  31311. //# sourceMappingURL=babylon.geometry.js.map
  31312. var BABYLON;
  31313. (function (BABYLON) {
  31314. var PostProcessManager = /** @class */ (function () {
  31315. function PostProcessManager(scene) {
  31316. this._vertexBuffers = {};
  31317. this._scene = scene;
  31318. }
  31319. PostProcessManager.prototype._prepareBuffers = function () {
  31320. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31321. return;
  31322. }
  31323. // VBO
  31324. var vertices = [];
  31325. vertices.push(1, 1);
  31326. vertices.push(-1, 1);
  31327. vertices.push(-1, -1);
  31328. vertices.push(1, -1);
  31329. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31330. this._buildIndexBuffer();
  31331. };
  31332. PostProcessManager.prototype._buildIndexBuffer = function () {
  31333. // Indices
  31334. var indices = [];
  31335. indices.push(0);
  31336. indices.push(1);
  31337. indices.push(2);
  31338. indices.push(0);
  31339. indices.push(2);
  31340. indices.push(3);
  31341. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31342. };
  31343. PostProcessManager.prototype._rebuild = function () {
  31344. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31345. if (!vb) {
  31346. return;
  31347. }
  31348. vb._rebuild();
  31349. this._buildIndexBuffer();
  31350. };
  31351. // Methods
  31352. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31353. if (sourceTexture === void 0) { sourceTexture = null; }
  31354. if (postProcesses === void 0) { postProcesses = null; }
  31355. var camera = this._scene.activeCamera;
  31356. if (!camera) {
  31357. return false;
  31358. }
  31359. var postProcesses = postProcesses || camera._postProcesses;
  31360. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31361. return false;
  31362. }
  31363. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31364. return true;
  31365. };
  31366. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31367. if (targetTexture === void 0) { targetTexture = null; }
  31368. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31369. if (!this._scene.activeCamera) {
  31370. return;
  31371. }
  31372. var engine = this._scene.getEngine();
  31373. for (var index = 0; index < postProcesses.length; index++) {
  31374. if (index < postProcesses.length - 1) {
  31375. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31376. }
  31377. else {
  31378. if (targetTexture) {
  31379. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31380. }
  31381. else {
  31382. engine.restoreDefaultFramebuffer();
  31383. }
  31384. }
  31385. var pp = postProcesses[index];
  31386. var effect = pp.apply();
  31387. if (effect) {
  31388. pp.onBeforeRenderObservable.notifyObservers(effect);
  31389. // VBOs
  31390. this._prepareBuffers();
  31391. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31392. // Draw order
  31393. engine.draw(true, 0, 6);
  31394. pp.onAfterRenderObservable.notifyObservers(effect);
  31395. }
  31396. }
  31397. // Restore depth buffer
  31398. engine.setDepthBuffer(true);
  31399. engine.setDepthWrite(true);
  31400. };
  31401. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31402. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31403. var camera = this._scene.activeCamera;
  31404. if (!camera) {
  31405. return;
  31406. }
  31407. postProcesses = postProcesses || camera._postProcesses;
  31408. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31409. return;
  31410. }
  31411. var engine = this._scene.getEngine();
  31412. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31413. if (index < len - 1) {
  31414. postProcesses[index + 1].activate(camera, targetTexture);
  31415. }
  31416. else {
  31417. if (targetTexture) {
  31418. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31419. }
  31420. else {
  31421. engine.restoreDefaultFramebuffer();
  31422. }
  31423. }
  31424. if (doNotPresent) {
  31425. break;
  31426. }
  31427. var pp = postProcesses[index];
  31428. var effect = pp.apply();
  31429. if (effect) {
  31430. pp.onBeforeRenderObservable.notifyObservers(effect);
  31431. // VBOs
  31432. this._prepareBuffers();
  31433. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31434. // Draw order
  31435. engine.draw(true, 0, 6);
  31436. pp.onAfterRenderObservable.notifyObservers(effect);
  31437. }
  31438. }
  31439. // Restore states
  31440. engine.setDepthBuffer(true);
  31441. engine.setDepthWrite(true);
  31442. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31443. };
  31444. PostProcessManager.prototype.dispose = function () {
  31445. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31446. if (buffer) {
  31447. buffer.dispose();
  31448. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31449. }
  31450. if (this._indexBuffer) {
  31451. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31452. this._indexBuffer = null;
  31453. }
  31454. };
  31455. return PostProcessManager;
  31456. }());
  31457. BABYLON.PostProcessManager = PostProcessManager;
  31458. })(BABYLON || (BABYLON = {}));
  31459. //# sourceMappingURL=babylon.postProcessManager.js.map
  31460. var BABYLON;
  31461. (function (BABYLON) {
  31462. /**
  31463. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31464. */
  31465. var PerformanceMonitor = /** @class */ (function () {
  31466. /**
  31467. * constructor
  31468. * @param frameSampleSize The number of samples required to saturate the sliding window
  31469. */
  31470. function PerformanceMonitor(frameSampleSize) {
  31471. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31472. this._enabled = true;
  31473. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31474. }
  31475. /**
  31476. * Samples current frame
  31477. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31478. */
  31479. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31480. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31481. if (!this._enabled)
  31482. return;
  31483. if (this._lastFrameTimeMs != null) {
  31484. var dt = timeMs - this._lastFrameTimeMs;
  31485. this._rollingFrameTime.add(dt);
  31486. }
  31487. this._lastFrameTimeMs = timeMs;
  31488. };
  31489. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31490. /**
  31491. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31492. * @return Average frame time in milliseconds
  31493. */
  31494. get: function () {
  31495. return this._rollingFrameTime.average;
  31496. },
  31497. enumerable: true,
  31498. configurable: true
  31499. });
  31500. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31501. /**
  31502. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31503. * @return Frame time variance in milliseconds squared
  31504. */
  31505. get: function () {
  31506. return this._rollingFrameTime.variance;
  31507. },
  31508. enumerable: true,
  31509. configurable: true
  31510. });
  31511. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31512. /**
  31513. * Returns the frame time of the most recent frame
  31514. * @return Frame time in milliseconds
  31515. */
  31516. get: function () {
  31517. return this._rollingFrameTime.history(0);
  31518. },
  31519. enumerable: true,
  31520. configurable: true
  31521. });
  31522. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31523. /**
  31524. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31525. * @return Framerate in frames per second
  31526. */
  31527. get: function () {
  31528. return 1000.0 / this._rollingFrameTime.average;
  31529. },
  31530. enumerable: true,
  31531. configurable: true
  31532. });
  31533. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31534. /**
  31535. * Returns the average framerate in frames per second using the most recent frame time
  31536. * @return Framerate in frames per second
  31537. */
  31538. get: function () {
  31539. var history = this._rollingFrameTime.history(0);
  31540. if (history === 0) {
  31541. return 0;
  31542. }
  31543. return 1000.0 / history;
  31544. },
  31545. enumerable: true,
  31546. configurable: true
  31547. });
  31548. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31549. /**
  31550. * Returns true if enough samples have been taken to completely fill the sliding window
  31551. * @return true if saturated
  31552. */
  31553. get: function () {
  31554. return this._rollingFrameTime.isSaturated();
  31555. },
  31556. enumerable: true,
  31557. configurable: true
  31558. });
  31559. /**
  31560. * Enables contributions to the sliding window sample set
  31561. */
  31562. PerformanceMonitor.prototype.enable = function () {
  31563. this._enabled = true;
  31564. };
  31565. /**
  31566. * Disables contributions to the sliding window sample set
  31567. * Samples will not be interpolated over the disabled period
  31568. */
  31569. PerformanceMonitor.prototype.disable = function () {
  31570. this._enabled = false;
  31571. //clear last sample to avoid interpolating over the disabled period when next enabled
  31572. this._lastFrameTimeMs = null;
  31573. this._lastChangeTimeMs = null;
  31574. };
  31575. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31576. /**
  31577. * Returns true if sampling is enabled
  31578. * @return true if enabled
  31579. */
  31580. get: function () {
  31581. return this._enabled;
  31582. },
  31583. enumerable: true,
  31584. configurable: true
  31585. });
  31586. /**
  31587. * Resets performance monitor
  31588. */
  31589. PerformanceMonitor.prototype.reset = function () {
  31590. //clear last sample to avoid interpolating over the disabled period when next enabled
  31591. this._lastFrameTimeMs = null;
  31592. this._lastChangeTimeMs = null;
  31593. //wipe record
  31594. this._rollingFrameTime.reset();
  31595. };
  31596. return PerformanceMonitor;
  31597. }());
  31598. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31599. /**
  31600. * RollingAverage
  31601. *
  31602. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31603. */
  31604. var RollingAverage = /** @class */ (function () {
  31605. /**
  31606. * constructor
  31607. * @param length The number of samples required to saturate the sliding window
  31608. */
  31609. function RollingAverage(length) {
  31610. this._samples = new Array(length);
  31611. this.reset();
  31612. }
  31613. /**
  31614. * Adds a sample to the sample set
  31615. * @param v The sample value
  31616. */
  31617. RollingAverage.prototype.add = function (v) {
  31618. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31619. var delta;
  31620. //we need to check if we've already wrapped round
  31621. if (this.isSaturated()) {
  31622. //remove bottom of stack from mean
  31623. var bottomValue = this._samples[this._pos];
  31624. delta = bottomValue - this.average;
  31625. this.average -= delta / (this._sampleCount - 1);
  31626. this._m2 -= delta * (bottomValue - this.average);
  31627. }
  31628. else {
  31629. this._sampleCount++;
  31630. }
  31631. //add new value to mean
  31632. delta = v - this.average;
  31633. this.average += delta / (this._sampleCount);
  31634. this._m2 += delta * (v - this.average);
  31635. //set the new variance
  31636. this.variance = this._m2 / (this._sampleCount - 1);
  31637. this._samples[this._pos] = v;
  31638. this._pos++;
  31639. this._pos %= this._samples.length; //positive wrap around
  31640. };
  31641. /**
  31642. * Returns previously added values or null if outside of history or outside the sliding window domain
  31643. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  31644. * @return Value previously recorded with add() or null if outside of range
  31645. */
  31646. RollingAverage.prototype.history = function (i) {
  31647. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  31648. return 0;
  31649. }
  31650. var i0 = this._wrapPosition(this._pos - 1.0);
  31651. return this._samples[this._wrapPosition(i0 - i)];
  31652. };
  31653. /**
  31654. * Returns true if enough samples have been taken to completely fill the sliding window
  31655. * @return true if sample-set saturated
  31656. */
  31657. RollingAverage.prototype.isSaturated = function () {
  31658. return this._sampleCount >= this._samples.length;
  31659. };
  31660. /**
  31661. * Resets the rolling average (equivalent to 0 samples taken so far)
  31662. */
  31663. RollingAverage.prototype.reset = function () {
  31664. this.average = 0;
  31665. this.variance = 0;
  31666. this._sampleCount = 0;
  31667. this._pos = 0;
  31668. this._m2 = 0;
  31669. };
  31670. /**
  31671. * Wraps a value around the sample range boundaries
  31672. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  31673. * @return Wrapped position in sample range
  31674. */
  31675. RollingAverage.prototype._wrapPosition = function (i) {
  31676. var max = this._samples.length;
  31677. return ((i % max) + max) % max;
  31678. };
  31679. return RollingAverage;
  31680. }());
  31681. BABYLON.RollingAverage = RollingAverage;
  31682. })(BABYLON || (BABYLON = {}));
  31683. //# sourceMappingURL=babylon.performanceMonitor.js.map
  31684. var BABYLON;
  31685. (function (BABYLON) {
  31686. /**
  31687. * This groups together the common properties used for image processing either in direct forward pass
  31688. * or through post processing effect depending on the use of the image processing pipeline in your scene
  31689. * or not.
  31690. */
  31691. var ImageProcessingConfiguration = /** @class */ (function () {
  31692. function ImageProcessingConfiguration() {
  31693. /**
  31694. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  31695. */
  31696. this.colorCurves = new BABYLON.ColorCurves();
  31697. this._colorCurvesEnabled = false;
  31698. this._colorGradingEnabled = false;
  31699. this._colorGradingWithGreenDepth = true;
  31700. this._colorGradingBGR = true;
  31701. this._exposure = 1.0;
  31702. this._toneMappingEnabled = false;
  31703. this._contrast = 1.0;
  31704. /**
  31705. * Vignette stretch size.
  31706. */
  31707. this.vignetteStretch = 0;
  31708. /**
  31709. * Vignette centre X Offset.
  31710. */
  31711. this.vignetteCentreX = 0;
  31712. /**
  31713. * Vignette centre Y Offset.
  31714. */
  31715. this.vignetteCentreY = 0;
  31716. /**
  31717. * Vignette weight or intensity of the vignette effect.
  31718. */
  31719. this.vignetteWeight = 1.5;
  31720. /**
  31721. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  31722. * if vignetteEnabled is set to true.
  31723. */
  31724. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  31725. /**
  31726. * Camera field of view used by the Vignette effect.
  31727. */
  31728. this.vignetteCameraFov = 0.5;
  31729. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  31730. this._vignetteEnabled = false;
  31731. this._applyByPostProcess = false;
  31732. /**
  31733. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  31734. * @type {BABYLON.Observable}
  31735. */
  31736. this.onUpdateParameters = new BABYLON.Observable();
  31737. }
  31738. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  31739. /**
  31740. * Gets wether the color curves effect is enabled.
  31741. */
  31742. get: function () {
  31743. return this._colorCurvesEnabled;
  31744. },
  31745. /**
  31746. * Sets wether the color curves effect is enabled.
  31747. */
  31748. set: function (value) {
  31749. if (this._colorCurvesEnabled === value) {
  31750. return;
  31751. }
  31752. this._colorCurvesEnabled = value;
  31753. this._updateParameters();
  31754. },
  31755. enumerable: true,
  31756. configurable: true
  31757. });
  31758. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  31759. /**
  31760. * Gets wether the color grading effect is enabled.
  31761. */
  31762. get: function () {
  31763. return this._colorGradingEnabled;
  31764. },
  31765. /**
  31766. * Sets wether the color grading effect is enabled.
  31767. */
  31768. set: function (value) {
  31769. if (this._colorGradingEnabled === value) {
  31770. return;
  31771. }
  31772. this._colorGradingEnabled = value;
  31773. this._updateParameters();
  31774. },
  31775. enumerable: true,
  31776. configurable: true
  31777. });
  31778. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  31779. /**
  31780. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  31781. */
  31782. get: function () {
  31783. return this._colorGradingWithGreenDepth;
  31784. },
  31785. /**
  31786. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  31787. */
  31788. set: function (value) {
  31789. if (this._colorGradingWithGreenDepth === value) {
  31790. return;
  31791. }
  31792. this._colorGradingWithGreenDepth = value;
  31793. this._updateParameters();
  31794. },
  31795. enumerable: true,
  31796. configurable: true
  31797. });
  31798. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  31799. /**
  31800. * Gets wether the color grading texture contains BGR values.
  31801. */
  31802. get: function () {
  31803. return this._colorGradingBGR;
  31804. },
  31805. /**
  31806. * Sets wether the color grading texture contains BGR values.
  31807. */
  31808. set: function (value) {
  31809. if (this._colorGradingBGR === value) {
  31810. return;
  31811. }
  31812. this._colorGradingBGR = value;
  31813. this._updateParameters();
  31814. },
  31815. enumerable: true,
  31816. configurable: true
  31817. });
  31818. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  31819. /**
  31820. * Gets the Exposure used in the effect.
  31821. */
  31822. get: function () {
  31823. return this._exposure;
  31824. },
  31825. /**
  31826. * Sets the Exposure used in the effect.
  31827. */
  31828. set: function (value) {
  31829. if (this._exposure === value) {
  31830. return;
  31831. }
  31832. this._exposure = value;
  31833. this._updateParameters();
  31834. },
  31835. enumerable: true,
  31836. configurable: true
  31837. });
  31838. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  31839. /**
  31840. * Gets wether the tone mapping effect is enabled.
  31841. */
  31842. get: function () {
  31843. return this._toneMappingEnabled;
  31844. },
  31845. /**
  31846. * Sets wether the tone mapping effect is enabled.
  31847. */
  31848. set: function (value) {
  31849. if (this._toneMappingEnabled === value) {
  31850. return;
  31851. }
  31852. this._toneMappingEnabled = value;
  31853. this._updateParameters();
  31854. },
  31855. enumerable: true,
  31856. configurable: true
  31857. });
  31858. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  31859. /**
  31860. * Gets the contrast used in the effect.
  31861. */
  31862. get: function () {
  31863. return this._contrast;
  31864. },
  31865. /**
  31866. * Sets the contrast used in the effect.
  31867. */
  31868. set: function (value) {
  31869. if (this._contrast === value) {
  31870. return;
  31871. }
  31872. this._contrast = value;
  31873. this._updateParameters();
  31874. },
  31875. enumerable: true,
  31876. configurable: true
  31877. });
  31878. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  31879. /**
  31880. * Gets the vignette blend mode allowing different kind of effect.
  31881. */
  31882. get: function () {
  31883. return this._vignetteBlendMode;
  31884. },
  31885. /**
  31886. * Sets the vignette blend mode allowing different kind of effect.
  31887. */
  31888. set: function (value) {
  31889. if (this._vignetteBlendMode === value) {
  31890. return;
  31891. }
  31892. this._vignetteBlendMode = value;
  31893. this._updateParameters();
  31894. },
  31895. enumerable: true,
  31896. configurable: true
  31897. });
  31898. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  31899. /**
  31900. * Gets wether the vignette effect is enabled.
  31901. */
  31902. get: function () {
  31903. return this._vignetteEnabled;
  31904. },
  31905. /**
  31906. * Sets wether the vignette effect is enabled.
  31907. */
  31908. set: function (value) {
  31909. if (this._vignetteEnabled === value) {
  31910. return;
  31911. }
  31912. this._vignetteEnabled = value;
  31913. this._updateParameters();
  31914. },
  31915. enumerable: true,
  31916. configurable: true
  31917. });
  31918. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  31919. /**
  31920. * Gets wether the image processing is applied through a post process or not.
  31921. */
  31922. get: function () {
  31923. return this._applyByPostProcess;
  31924. },
  31925. /**
  31926. * Sets wether the image processing is applied through a post process or not.
  31927. */
  31928. set: function (value) {
  31929. if (this._applyByPostProcess === value) {
  31930. return;
  31931. }
  31932. this._applyByPostProcess = value;
  31933. this._updateParameters();
  31934. },
  31935. enumerable: true,
  31936. configurable: true
  31937. });
  31938. /**
  31939. * Method called each time the image processing information changes requires to recompile the effect.
  31940. */
  31941. ImageProcessingConfiguration.prototype._updateParameters = function () {
  31942. this.onUpdateParameters.notifyObservers(this);
  31943. };
  31944. ImageProcessingConfiguration.prototype.getClassName = function () {
  31945. return "ImageProcessingConfiguration";
  31946. };
  31947. /**
  31948. * Prepare the list of uniforms associated with the Image Processing effects.
  31949. * @param uniformsList The list of uniforms used in the effect
  31950. * @param defines the list of defines currently in use
  31951. */
  31952. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  31953. if (defines.EXPOSURE) {
  31954. uniforms.push("exposureLinear");
  31955. }
  31956. if (defines.CONTRAST) {
  31957. uniforms.push("contrast");
  31958. }
  31959. if (defines.COLORGRADING) {
  31960. uniforms.push("colorTransformSettings");
  31961. }
  31962. if (defines.VIGNETTE) {
  31963. uniforms.push("vInverseScreenSize");
  31964. uniforms.push("vignetteSettings1");
  31965. uniforms.push("vignetteSettings2");
  31966. }
  31967. if (defines.COLORCURVES) {
  31968. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  31969. }
  31970. };
  31971. /**
  31972. * Prepare the list of samplers associated with the Image Processing effects.
  31973. * @param uniformsList The list of uniforms used in the effect
  31974. * @param defines the list of defines currently in use
  31975. */
  31976. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  31977. if (defines.COLORGRADING) {
  31978. samplersList.push("txColorTransform");
  31979. }
  31980. };
  31981. /**
  31982. * Prepare the list of defines associated to the shader.
  31983. * @param defines the list of defines to complete
  31984. */
  31985. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  31986. if (forPostProcess === void 0) { forPostProcess = false; }
  31987. if (forPostProcess !== this.applyByPostProcess) {
  31988. defines.VIGNETTE = false;
  31989. defines.TONEMAPPING = false;
  31990. defines.CONTRAST = false;
  31991. defines.EXPOSURE = false;
  31992. defines.COLORCURVES = false;
  31993. defines.COLORGRADING = false;
  31994. defines.COLORGRADING3D = false;
  31995. defines.IMAGEPROCESSING = false;
  31996. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  31997. return;
  31998. }
  31999. defines.VIGNETTE = this.vignetteEnabled;
  32000. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32001. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32002. defines.TONEMAPPING = this.toneMappingEnabled;
  32003. defines.CONTRAST = (this.contrast !== 1.0);
  32004. defines.EXPOSURE = (this.exposure !== 1.0);
  32005. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32006. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32007. if (defines.COLORGRADING) {
  32008. var texture = this.colorGradingTexture;
  32009. defines.COLORGRADING3D = (texture.getScene().getEngine().webGLVersion > 1) ? true : false;
  32010. }
  32011. else {
  32012. defines.COLORGRADING3D = false;
  32013. }
  32014. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32015. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32016. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32017. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32018. };
  32019. /**
  32020. * Returns true if all the image processing information are ready.
  32021. */
  32022. ImageProcessingConfiguration.prototype.isReady = function () {
  32023. // Color Grading texure can not be none blocking.
  32024. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32025. };
  32026. /**
  32027. * Binds the image processing to the shader.
  32028. * @param effect The effect to bind to
  32029. */
  32030. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32031. if (aspectRatio === void 0) { aspectRatio = 1; }
  32032. // Color Curves
  32033. if (this._colorCurvesEnabled && this.colorCurves) {
  32034. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32035. }
  32036. // Vignette
  32037. if (this._vignetteEnabled) {
  32038. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32039. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32040. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32041. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32042. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32043. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32044. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32045. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32046. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32047. var vignettePower = -2.0 * this.vignetteWeight;
  32048. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32049. }
  32050. // Exposure
  32051. effect.setFloat("exposureLinear", this.exposure);
  32052. // Contrast
  32053. effect.setFloat("contrast", this.contrast);
  32054. // Color transform settings
  32055. if (this.colorGradingTexture) {
  32056. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32057. var textureSize = this.colorGradingTexture.getSize().height;
  32058. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32059. 0.5 / textureSize, // textureOffset
  32060. textureSize, // textureSize
  32061. this.colorGradingTexture.level // weight
  32062. );
  32063. }
  32064. };
  32065. /**
  32066. * Clones the current image processing instance.
  32067. * @return The cloned image processing
  32068. */
  32069. ImageProcessingConfiguration.prototype.clone = function () {
  32070. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32071. };
  32072. /**
  32073. * Serializes the current image processing instance to a json representation.
  32074. * @return a JSON representation
  32075. */
  32076. ImageProcessingConfiguration.prototype.serialize = function () {
  32077. return BABYLON.SerializationHelper.Serialize(this);
  32078. };
  32079. /**
  32080. * Parses the image processing from a json representation.
  32081. * @param source the JSON source to parse
  32082. * @return The parsed image processing
  32083. */
  32084. ImageProcessingConfiguration.Parse = function (source) {
  32085. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32086. };
  32087. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32088. /**
  32089. * Used to apply the vignette as a mix with the pixel color.
  32090. */
  32091. get: function () {
  32092. return this._VIGNETTEMODE_MULTIPLY;
  32093. },
  32094. enumerable: true,
  32095. configurable: true
  32096. });
  32097. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32098. /**
  32099. * Used to apply the vignette as a replacement of the pixel color.
  32100. */
  32101. get: function () {
  32102. return this._VIGNETTEMODE_OPAQUE;
  32103. },
  32104. enumerable: true,
  32105. configurable: true
  32106. });
  32107. // Static constants associated to the image processing.
  32108. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32109. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32110. __decorate([
  32111. BABYLON.serializeAsColorCurves()
  32112. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32113. __decorate([
  32114. BABYLON.serialize()
  32115. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32116. __decorate([
  32117. BABYLON.serializeAsTexture()
  32118. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32119. __decorate([
  32120. BABYLON.serialize()
  32121. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32122. __decorate([
  32123. BABYLON.serialize()
  32124. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32125. __decorate([
  32126. BABYLON.serialize()
  32127. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32128. __decorate([
  32129. BABYLON.serialize()
  32130. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32131. __decorate([
  32132. BABYLON.serialize()
  32133. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32134. __decorate([
  32135. BABYLON.serialize()
  32136. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32137. __decorate([
  32138. BABYLON.serialize()
  32139. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32140. __decorate([
  32141. BABYLON.serialize()
  32142. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32143. __decorate([
  32144. BABYLON.serialize()
  32145. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32146. __decorate([
  32147. BABYLON.serialize()
  32148. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32149. __decorate([
  32150. BABYLON.serializeAsColor4()
  32151. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32152. __decorate([
  32153. BABYLON.serialize()
  32154. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32155. __decorate([
  32156. BABYLON.serialize()
  32157. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32158. __decorate([
  32159. BABYLON.serialize()
  32160. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32161. __decorate([
  32162. BABYLON.serialize()
  32163. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32164. return ImageProcessingConfiguration;
  32165. }());
  32166. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32167. })(BABYLON || (BABYLON = {}));
  32168. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32169. var BABYLON;
  32170. (function (BABYLON) {
  32171. /**
  32172. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32173. * It can help converting any input color in a desired output one. This can then be used to create effects
  32174. * from sepia, black and white to sixties or futuristic rendering...
  32175. *
  32176. * The only supported format is currently 3dl.
  32177. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32178. */
  32179. var ColorGradingTexture = /** @class */ (function (_super) {
  32180. __extends(ColorGradingTexture, _super);
  32181. /**
  32182. * Instantiates a ColorGradingTexture from the following parameters.
  32183. *
  32184. * @param url The location of the color gradind data (currently only supporting 3dl)
  32185. * @param scene The scene the texture will be used in
  32186. */
  32187. function ColorGradingTexture(url, scene) {
  32188. var _this = _super.call(this, scene) || this;
  32189. if (!url) {
  32190. return _this;
  32191. }
  32192. _this._engine = scene.getEngine();
  32193. _this._textureMatrix = BABYLON.Matrix.Identity();
  32194. _this.name = url;
  32195. _this.url = url;
  32196. _this.hasAlpha = false;
  32197. _this.isCube = false;
  32198. _this.is3D = _this._engine.webGLVersion > 1;
  32199. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32200. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32201. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32202. _this.anisotropicFilteringLevel = 1;
  32203. _this._texture = _this._getFromCache(url, true);
  32204. if (!_this._texture) {
  32205. if (!scene.useDelayedTextureLoading) {
  32206. _this.loadTexture();
  32207. }
  32208. else {
  32209. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32210. }
  32211. }
  32212. return _this;
  32213. }
  32214. /**
  32215. * Returns the texture matrix used in most of the material.
  32216. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32217. */
  32218. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32219. return this._textureMatrix;
  32220. };
  32221. /**
  32222. * Occurs when the file being loaded is a .3dl LUT file.
  32223. */
  32224. ColorGradingTexture.prototype.load3dlTexture = function () {
  32225. var engine = this._engine;
  32226. var texture;
  32227. if (engine.webGLVersion === 1) {
  32228. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32229. }
  32230. else {
  32231. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32232. }
  32233. this._texture = texture;
  32234. var callback = function (text) {
  32235. var data = null;
  32236. var tempData = null;
  32237. var line;
  32238. var lines = text.split('\n');
  32239. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32240. var maxColor = 0;
  32241. for (var i = 0; i < lines.length; i++) {
  32242. line = lines[i];
  32243. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32244. continue;
  32245. if (line.indexOf('#') === 0)
  32246. continue;
  32247. var words = line.split(" ");
  32248. if (size === 0) {
  32249. // Number of space + one
  32250. size = words.length;
  32251. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32252. tempData = new Float32Array(size * size * size * 4);
  32253. continue;
  32254. }
  32255. if (size != 0) {
  32256. var r = Math.max(parseInt(words[0]), 0);
  32257. var g = Math.max(parseInt(words[1]), 0);
  32258. var b = Math.max(parseInt(words[2]), 0);
  32259. maxColor = Math.max(r, maxColor);
  32260. maxColor = Math.max(g, maxColor);
  32261. maxColor = Math.max(b, maxColor);
  32262. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32263. if (tempData) {
  32264. tempData[pixelStorageIndex + 0] = r;
  32265. tempData[pixelStorageIndex + 1] = g;
  32266. tempData[pixelStorageIndex + 2] = b;
  32267. }
  32268. pixelIndexSlice++;
  32269. if (pixelIndexSlice % size == 0) {
  32270. pixelIndexH++;
  32271. pixelIndexSlice = 0;
  32272. if (pixelIndexH % size == 0) {
  32273. pixelIndexW++;
  32274. pixelIndexH = 0;
  32275. }
  32276. }
  32277. }
  32278. }
  32279. if (tempData && data) {
  32280. for (var i = 0; i < tempData.length; i++) {
  32281. if (i > 0 && (i + 1) % 4 === 0) {
  32282. data[i] = 255;
  32283. }
  32284. else {
  32285. var value = tempData[i];
  32286. data[i] = (value / maxColor * 255);
  32287. }
  32288. }
  32289. }
  32290. if (texture.is3D) {
  32291. texture.updateSize(size, size, size);
  32292. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32293. }
  32294. else {
  32295. texture.updateSize(size * size, size);
  32296. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32297. }
  32298. };
  32299. BABYLON.Tools.LoadFile(this.url, callback);
  32300. return this._texture;
  32301. };
  32302. /**
  32303. * Starts the loading process of the texture.
  32304. */
  32305. ColorGradingTexture.prototype.loadTexture = function () {
  32306. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32307. this.load3dlTexture();
  32308. }
  32309. };
  32310. /**
  32311. * Clones the color gradind texture.
  32312. */
  32313. ColorGradingTexture.prototype.clone = function () {
  32314. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32315. // Base texture
  32316. newTexture.level = this.level;
  32317. return newTexture;
  32318. };
  32319. /**
  32320. * Called during delayed load for textures.
  32321. */
  32322. ColorGradingTexture.prototype.delayLoad = function () {
  32323. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32324. return;
  32325. }
  32326. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32327. this._texture = this._getFromCache(this.url, true);
  32328. if (!this._texture) {
  32329. this.loadTexture();
  32330. }
  32331. };
  32332. /**
  32333. * Parses a color grading texture serialized by Babylon.
  32334. * @param parsedTexture The texture information being parsedTexture
  32335. * @param scene The scene to load the texture in
  32336. * @param rootUrl The root url of the data assets to load
  32337. * @return A color gradind texture
  32338. */
  32339. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32340. var texture = null;
  32341. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32342. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32343. texture.name = parsedTexture.name;
  32344. texture.level = parsedTexture.level;
  32345. }
  32346. return texture;
  32347. };
  32348. /**
  32349. * Serializes the LUT texture to json format.
  32350. */
  32351. ColorGradingTexture.prototype.serialize = function () {
  32352. if (!this.name) {
  32353. return null;
  32354. }
  32355. var serializationObject = {};
  32356. serializationObject.name = this.name;
  32357. serializationObject.level = this.level;
  32358. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32359. return serializationObject;
  32360. };
  32361. /**
  32362. * Empty line regex stored for GC.
  32363. */
  32364. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32365. return ColorGradingTexture;
  32366. }(BABYLON.BaseTexture));
  32367. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32368. })(BABYLON || (BABYLON = {}));
  32369. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32370. var BABYLON;
  32371. (function (BABYLON) {
  32372. /**
  32373. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32374. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32375. * 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;
  32376. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32377. */
  32378. var ColorCurves = /** @class */ (function () {
  32379. function ColorCurves() {
  32380. this._dirty = true;
  32381. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32382. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32383. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32384. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32385. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32386. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32387. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32388. this._globalHue = 30;
  32389. this._globalDensity = 0;
  32390. this._globalSaturation = 0;
  32391. this._globalExposure = 0;
  32392. this._highlightsHue = 30;
  32393. this._highlightsDensity = 0;
  32394. this._highlightsSaturation = 0;
  32395. this._highlightsExposure = 0;
  32396. this._midtonesHue = 30;
  32397. this._midtonesDensity = 0;
  32398. this._midtonesSaturation = 0;
  32399. this._midtonesExposure = 0;
  32400. this._shadowsHue = 30;
  32401. this._shadowsDensity = 0;
  32402. this._shadowsSaturation = 0;
  32403. this._shadowsExposure = 0;
  32404. }
  32405. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32406. /**
  32407. * Gets the global Hue value.
  32408. * 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).
  32409. */
  32410. get: function () {
  32411. return this._globalHue;
  32412. },
  32413. /**
  32414. * Sets the global Hue value.
  32415. * 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).
  32416. */
  32417. set: function (value) {
  32418. this._globalHue = value;
  32419. this._dirty = true;
  32420. },
  32421. enumerable: true,
  32422. configurable: true
  32423. });
  32424. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32425. /**
  32426. * Gets the global Density value.
  32427. * 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.
  32428. * Values less than zero provide a filter of opposite hue.
  32429. */
  32430. get: function () {
  32431. return this._globalDensity;
  32432. },
  32433. /**
  32434. * Sets the global Density value.
  32435. * 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.
  32436. * Values less than zero provide a filter of opposite hue.
  32437. */
  32438. set: function (value) {
  32439. this._globalDensity = value;
  32440. this._dirty = true;
  32441. },
  32442. enumerable: true,
  32443. configurable: true
  32444. });
  32445. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32446. /**
  32447. * Gets the global Saturation value.
  32448. * 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.
  32449. */
  32450. get: function () {
  32451. return this._globalSaturation;
  32452. },
  32453. /**
  32454. * Sets the global Saturation value.
  32455. * 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.
  32456. */
  32457. set: function (value) {
  32458. this._globalSaturation = value;
  32459. this._dirty = true;
  32460. },
  32461. enumerable: true,
  32462. configurable: true
  32463. });
  32464. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32465. /**
  32466. * Gets the highlights Hue value.
  32467. * 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).
  32468. */
  32469. get: function () {
  32470. return this._highlightsHue;
  32471. },
  32472. /**
  32473. * Sets the highlights Hue value.
  32474. * 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).
  32475. */
  32476. set: function (value) {
  32477. this._highlightsHue = value;
  32478. this._dirty = true;
  32479. },
  32480. enumerable: true,
  32481. configurable: true
  32482. });
  32483. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32484. /**
  32485. * Gets the highlights Density value.
  32486. * 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.
  32487. * Values less than zero provide a filter of opposite hue.
  32488. */
  32489. get: function () {
  32490. return this._highlightsDensity;
  32491. },
  32492. /**
  32493. * Sets the highlights Density value.
  32494. * 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.
  32495. * Values less than zero provide a filter of opposite hue.
  32496. */
  32497. set: function (value) {
  32498. this._highlightsDensity = value;
  32499. this._dirty = true;
  32500. },
  32501. enumerable: true,
  32502. configurable: true
  32503. });
  32504. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32505. /**
  32506. * Gets the highlights Saturation value.
  32507. * 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.
  32508. */
  32509. get: function () {
  32510. return this._highlightsSaturation;
  32511. },
  32512. /**
  32513. * Sets the highlights Saturation value.
  32514. * 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.
  32515. */
  32516. set: function (value) {
  32517. this._highlightsSaturation = value;
  32518. this._dirty = true;
  32519. },
  32520. enumerable: true,
  32521. configurable: true
  32522. });
  32523. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32524. /**
  32525. * Gets the highlights Exposure value.
  32526. * 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.
  32527. */
  32528. get: function () {
  32529. return this._highlightsExposure;
  32530. },
  32531. /**
  32532. * Sets the highlights Exposure value.
  32533. * 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.
  32534. */
  32535. set: function (value) {
  32536. this._highlightsExposure = value;
  32537. this._dirty = true;
  32538. },
  32539. enumerable: true,
  32540. configurable: true
  32541. });
  32542. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32543. /**
  32544. * Gets the midtones Hue value.
  32545. * 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).
  32546. */
  32547. get: function () {
  32548. return this._midtonesHue;
  32549. },
  32550. /**
  32551. * Sets the midtones Hue value.
  32552. * 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).
  32553. */
  32554. set: function (value) {
  32555. this._midtonesHue = value;
  32556. this._dirty = true;
  32557. },
  32558. enumerable: true,
  32559. configurable: true
  32560. });
  32561. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32562. /**
  32563. * Gets the midtones Density value.
  32564. * 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.
  32565. * Values less than zero provide a filter of opposite hue.
  32566. */
  32567. get: function () {
  32568. return this._midtonesDensity;
  32569. },
  32570. /**
  32571. * Sets the midtones Density value.
  32572. * 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.
  32573. * Values less than zero provide a filter of opposite hue.
  32574. */
  32575. set: function (value) {
  32576. this._midtonesDensity = value;
  32577. this._dirty = true;
  32578. },
  32579. enumerable: true,
  32580. configurable: true
  32581. });
  32582. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32583. /**
  32584. * Gets the midtones Saturation value.
  32585. * 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.
  32586. */
  32587. get: function () {
  32588. return this._midtonesSaturation;
  32589. },
  32590. /**
  32591. * Sets the midtones Saturation value.
  32592. * 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.
  32593. */
  32594. set: function (value) {
  32595. this._midtonesSaturation = value;
  32596. this._dirty = true;
  32597. },
  32598. enumerable: true,
  32599. configurable: true
  32600. });
  32601. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32602. /**
  32603. * Gets the midtones Exposure value.
  32604. * 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.
  32605. */
  32606. get: function () {
  32607. return this._midtonesExposure;
  32608. },
  32609. /**
  32610. * Sets the midtones Exposure value.
  32611. * 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.
  32612. */
  32613. set: function (value) {
  32614. this._midtonesExposure = value;
  32615. this._dirty = true;
  32616. },
  32617. enumerable: true,
  32618. configurable: true
  32619. });
  32620. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32621. /**
  32622. * Gets the shadows Hue value.
  32623. * 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).
  32624. */
  32625. get: function () {
  32626. return this._shadowsHue;
  32627. },
  32628. /**
  32629. * Sets the shadows Hue value.
  32630. * 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).
  32631. */
  32632. set: function (value) {
  32633. this._shadowsHue = value;
  32634. this._dirty = true;
  32635. },
  32636. enumerable: true,
  32637. configurable: true
  32638. });
  32639. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  32640. /**
  32641. * Gets the shadows Density value.
  32642. * 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.
  32643. * Values less than zero provide a filter of opposite hue.
  32644. */
  32645. get: function () {
  32646. return this._shadowsDensity;
  32647. },
  32648. /**
  32649. * Sets the shadows Density value.
  32650. * 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.
  32651. * Values less than zero provide a filter of opposite hue.
  32652. */
  32653. set: function (value) {
  32654. this._shadowsDensity = value;
  32655. this._dirty = true;
  32656. },
  32657. enumerable: true,
  32658. configurable: true
  32659. });
  32660. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  32661. /**
  32662. * Gets the shadows Saturation value.
  32663. * 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.
  32664. */
  32665. get: function () {
  32666. return this._shadowsSaturation;
  32667. },
  32668. /**
  32669. * Sets the shadows Saturation value.
  32670. * 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.
  32671. */
  32672. set: function (value) {
  32673. this._shadowsSaturation = value;
  32674. this._dirty = true;
  32675. },
  32676. enumerable: true,
  32677. configurable: true
  32678. });
  32679. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  32680. /**
  32681. * Gets the shadows Exposure value.
  32682. * 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.
  32683. */
  32684. get: function () {
  32685. return this._shadowsExposure;
  32686. },
  32687. /**
  32688. * Sets the shadows Exposure value.
  32689. * 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.
  32690. */
  32691. set: function (value) {
  32692. this._shadowsExposure = value;
  32693. this._dirty = true;
  32694. },
  32695. enumerable: true,
  32696. configurable: true
  32697. });
  32698. ColorCurves.prototype.getClassName = function () {
  32699. return "ColorCurves";
  32700. };
  32701. /**
  32702. * Binds the color curves to the shader.
  32703. * @param colorCurves The color curve to bind
  32704. * @param effect The effect to bind to
  32705. */
  32706. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  32707. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  32708. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  32709. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  32710. if (colorCurves._dirty) {
  32711. colorCurves._dirty = false;
  32712. // Fill in global info.
  32713. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  32714. // Compute highlights info.
  32715. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  32716. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  32717. // Compute midtones info.
  32718. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  32719. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  32720. // Compute shadows info.
  32721. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  32722. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  32723. // Compute deltas (neutral is midtones).
  32724. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  32725. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  32726. }
  32727. if (effect) {
  32728. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  32729. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  32730. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  32731. }
  32732. };
  32733. /**
  32734. * Prepare the list of uniforms associated with the ColorCurves effects.
  32735. * @param uniformsList The list of uniforms used in the effect
  32736. */
  32737. ColorCurves.PrepareUniforms = function (uniformsList) {
  32738. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  32739. };
  32740. /**
  32741. * Returns color grading data based on a hue, density, saturation and exposure value.
  32742. * @param filterHue The hue of the color filter.
  32743. * @param filterDensity The density of the color filter.
  32744. * @param saturation The saturation.
  32745. * @param exposure The exposure.
  32746. * @param result The result data container.
  32747. */
  32748. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  32749. if (hue == null) {
  32750. return;
  32751. }
  32752. hue = ColorCurves.clamp(hue, 0, 360);
  32753. density = ColorCurves.clamp(density, -100, 100);
  32754. saturation = ColorCurves.clamp(saturation, -100, 100);
  32755. exposure = ColorCurves.clamp(exposure, -100, 100);
  32756. // Remap the slider/config filter density with non-linear mapping and also scale by half
  32757. // so that the maximum filter density is only 50% control. This provides fine control
  32758. // for small values and reasonable range.
  32759. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  32760. density *= 0.5;
  32761. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  32762. if (density < 0) {
  32763. density *= -1;
  32764. hue = (hue + 180) % 360;
  32765. }
  32766. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  32767. result.scaleToRef(2, result);
  32768. result.a = 1 + 0.01 * saturation;
  32769. };
  32770. /**
  32771. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  32772. * @param value The input slider value in range [-100,100].
  32773. * @returns Adjusted value.
  32774. */
  32775. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  32776. value /= 100;
  32777. var x = Math.abs(value);
  32778. x = Math.pow(x, 2);
  32779. if (value < 0) {
  32780. x *= -1;
  32781. }
  32782. x *= 100;
  32783. return x;
  32784. };
  32785. /**
  32786. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  32787. * @param hue The hue (H) input.
  32788. * @param saturation The saturation (S) input.
  32789. * @param brightness The brightness (B) input.
  32790. * @result An RGBA color represented as Vector4.
  32791. */
  32792. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  32793. var h = ColorCurves.clamp(hue, 0, 360);
  32794. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  32795. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  32796. if (s === 0) {
  32797. result.r = v;
  32798. result.g = v;
  32799. result.b = v;
  32800. }
  32801. else {
  32802. // sector 0 to 5
  32803. h /= 60;
  32804. var i = Math.floor(h);
  32805. // fractional part of h
  32806. var f = h - i;
  32807. var p = v * (1 - s);
  32808. var q = v * (1 - s * f);
  32809. var t = v * (1 - s * (1 - f));
  32810. switch (i) {
  32811. case 0:
  32812. result.r = v;
  32813. result.g = t;
  32814. result.b = p;
  32815. break;
  32816. case 1:
  32817. result.r = q;
  32818. result.g = v;
  32819. result.b = p;
  32820. break;
  32821. case 2:
  32822. result.r = p;
  32823. result.g = v;
  32824. result.b = t;
  32825. break;
  32826. case 3:
  32827. result.r = p;
  32828. result.g = q;
  32829. result.b = v;
  32830. break;
  32831. case 4:
  32832. result.r = t;
  32833. result.g = p;
  32834. result.b = v;
  32835. break;
  32836. default:// case 5:
  32837. result.r = v;
  32838. result.g = p;
  32839. result.b = q;
  32840. break;
  32841. }
  32842. }
  32843. result.a = 1;
  32844. };
  32845. /**
  32846. * Returns a value clamped between min and max
  32847. * @param value The value to clamp
  32848. * @param min The minimum of value
  32849. * @param max The maximum of value
  32850. * @returns The clamped value.
  32851. */
  32852. ColorCurves.clamp = function (value, min, max) {
  32853. return Math.min(Math.max(value, min), max);
  32854. };
  32855. /**
  32856. * Clones the current color curve instance.
  32857. * @return The cloned curves
  32858. */
  32859. ColorCurves.prototype.clone = function () {
  32860. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  32861. };
  32862. /**
  32863. * Serializes the current color curve instance to a json representation.
  32864. * @return a JSON representation
  32865. */
  32866. ColorCurves.prototype.serialize = function () {
  32867. return BABYLON.SerializationHelper.Serialize(this);
  32868. };
  32869. /**
  32870. * Parses the color curve from a json representation.
  32871. * @param source the JSON source to parse
  32872. * @return The parsed curves
  32873. */
  32874. ColorCurves.Parse = function (source) {
  32875. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  32876. };
  32877. __decorate([
  32878. BABYLON.serialize()
  32879. ], ColorCurves.prototype, "_globalHue", void 0);
  32880. __decorate([
  32881. BABYLON.serialize()
  32882. ], ColorCurves.prototype, "_globalDensity", void 0);
  32883. __decorate([
  32884. BABYLON.serialize()
  32885. ], ColorCurves.prototype, "_globalSaturation", void 0);
  32886. __decorate([
  32887. BABYLON.serialize()
  32888. ], ColorCurves.prototype, "_globalExposure", void 0);
  32889. __decorate([
  32890. BABYLON.serialize()
  32891. ], ColorCurves.prototype, "_highlightsHue", void 0);
  32892. __decorate([
  32893. BABYLON.serialize()
  32894. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  32895. __decorate([
  32896. BABYLON.serialize()
  32897. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  32898. __decorate([
  32899. BABYLON.serialize()
  32900. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  32901. __decorate([
  32902. BABYLON.serialize()
  32903. ], ColorCurves.prototype, "_midtonesHue", void 0);
  32904. __decorate([
  32905. BABYLON.serialize()
  32906. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  32907. __decorate([
  32908. BABYLON.serialize()
  32909. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  32910. __decorate([
  32911. BABYLON.serialize()
  32912. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  32913. return ColorCurves;
  32914. }());
  32915. BABYLON.ColorCurves = ColorCurves;
  32916. })(BABYLON || (BABYLON = {}));
  32917. //# sourceMappingURL=babylon.colorCurves.js.map
  32918. var BABYLON;
  32919. (function (BABYLON) {
  32920. var StandardMaterialDefines = /** @class */ (function (_super) {
  32921. __extends(StandardMaterialDefines, _super);
  32922. function StandardMaterialDefines() {
  32923. var _this = _super.call(this) || this;
  32924. _this.MAINUV1 = false;
  32925. _this.MAINUV2 = false;
  32926. _this.DIFFUSE = false;
  32927. _this.DIFFUSEDIRECTUV = 0;
  32928. _this.AMBIENT = false;
  32929. _this.AMBIENTDIRECTUV = 0;
  32930. _this.OPACITY = false;
  32931. _this.OPACITYDIRECTUV = 0;
  32932. _this.OPACITYRGB = false;
  32933. _this.REFLECTION = false;
  32934. _this.EMISSIVE = false;
  32935. _this.EMISSIVEDIRECTUV = 0;
  32936. _this.SPECULAR = false;
  32937. _this.SPECULARDIRECTUV = 0;
  32938. _this.BUMP = false;
  32939. _this.BUMPDIRECTUV = 0;
  32940. _this.PARALLAX = false;
  32941. _this.PARALLAXOCCLUSION = false;
  32942. _this.SPECULAROVERALPHA = false;
  32943. _this.CLIPPLANE = false;
  32944. _this.ALPHATEST = false;
  32945. _this.DEPTHPREPASS = false;
  32946. _this.ALPHAFROMDIFFUSE = false;
  32947. _this.POINTSIZE = false;
  32948. _this.FOG = false;
  32949. _this.SPECULARTERM = false;
  32950. _this.DIFFUSEFRESNEL = false;
  32951. _this.OPACITYFRESNEL = false;
  32952. _this.REFLECTIONFRESNEL = false;
  32953. _this.REFRACTIONFRESNEL = false;
  32954. _this.EMISSIVEFRESNEL = false;
  32955. _this.FRESNEL = false;
  32956. _this.NORMAL = false;
  32957. _this.UV1 = false;
  32958. _this.UV2 = false;
  32959. _this.VERTEXCOLOR = false;
  32960. _this.VERTEXALPHA = false;
  32961. _this.NUM_BONE_INFLUENCERS = 0;
  32962. _this.BonesPerMesh = 0;
  32963. _this.INSTANCES = false;
  32964. _this.GLOSSINESS = false;
  32965. _this.ROUGHNESS = false;
  32966. _this.EMISSIVEASILLUMINATION = false;
  32967. _this.LINKEMISSIVEWITHDIFFUSE = false;
  32968. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  32969. _this.LIGHTMAP = false;
  32970. _this.LIGHTMAPDIRECTUV = 0;
  32971. _this.USELIGHTMAPASSHADOWMAP = false;
  32972. _this.REFLECTIONMAP_3D = false;
  32973. _this.REFLECTIONMAP_SPHERICAL = false;
  32974. _this.REFLECTIONMAP_PLANAR = false;
  32975. _this.REFLECTIONMAP_CUBIC = false;
  32976. _this.REFLECTIONMAP_PROJECTION = false;
  32977. _this.REFLECTIONMAP_SKYBOX = false;
  32978. _this.REFLECTIONMAP_EXPLICIT = false;
  32979. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32980. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32981. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32982. _this.INVERTCUBICMAP = false;
  32983. _this.LOGARITHMICDEPTH = false;
  32984. _this.REFRACTION = false;
  32985. _this.REFRACTIONMAP_3D = false;
  32986. _this.REFLECTIONOVERALPHA = false;
  32987. _this.TWOSIDEDLIGHTING = false;
  32988. _this.SHADOWFLOAT = false;
  32989. _this.MORPHTARGETS = false;
  32990. _this.MORPHTARGETS_NORMAL = false;
  32991. _this.MORPHTARGETS_TANGENT = false;
  32992. _this.NUM_MORPH_INFLUENCERS = 0;
  32993. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  32994. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  32995. _this.IMAGEPROCESSING = false;
  32996. _this.VIGNETTE = false;
  32997. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  32998. _this.VIGNETTEBLENDMODEOPAQUE = false;
  32999. _this.TONEMAPPING = false;
  33000. _this.CONTRAST = false;
  33001. _this.COLORCURVES = false;
  33002. _this.COLORGRADING = false;
  33003. _this.COLORGRADING3D = false;
  33004. _this.SAMPLER3DGREENDEPTH = false;
  33005. _this.SAMPLER3DBGRMAP = false;
  33006. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33007. _this.EXPOSURE = false;
  33008. _this.rebuild();
  33009. return _this;
  33010. }
  33011. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33012. var modes = [
  33013. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33014. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33015. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33016. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33017. ];
  33018. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33019. var mode = modes_1[_i];
  33020. this[mode] = (mode === modeToEnable);
  33021. }
  33022. };
  33023. return StandardMaterialDefines;
  33024. }(BABYLON.MaterialDefines));
  33025. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33026. var StandardMaterial = /** @class */ (function (_super) {
  33027. __extends(StandardMaterial, _super);
  33028. function StandardMaterial(name, scene) {
  33029. var _this = _super.call(this, name, scene) || this;
  33030. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33031. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33032. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33033. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33034. _this.specularPower = 64;
  33035. _this._useAlphaFromDiffuseTexture = false;
  33036. _this._useEmissiveAsIllumination = false;
  33037. _this._linkEmissiveWithDiffuse = false;
  33038. _this._useSpecularOverAlpha = false;
  33039. _this._useReflectionOverAlpha = false;
  33040. _this._disableLighting = false;
  33041. _this._useParallax = false;
  33042. _this._useParallaxOcclusion = false;
  33043. _this.parallaxScaleBias = 0.05;
  33044. _this._roughness = 0;
  33045. _this.indexOfRefraction = 0.98;
  33046. _this.invertRefractionY = true;
  33047. _this._useLightmapAsShadowmap = false;
  33048. _this._useReflectionFresnelFromSpecular = false;
  33049. _this._useGlossinessFromSpecularMapAlpha = false;
  33050. _this._maxSimultaneousLights = 4;
  33051. /**
  33052. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33053. */
  33054. _this._invertNormalMapX = false;
  33055. /**
  33056. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33057. */
  33058. _this._invertNormalMapY = false;
  33059. /**
  33060. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33061. */
  33062. _this._twoSidedLighting = false;
  33063. _this._renderTargets = new BABYLON.SmartArray(16);
  33064. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33065. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33066. // Setup the default processing configuration to the scene.
  33067. _this._attachImageProcessingConfiguration(null);
  33068. _this.getRenderTargetTextures = function () {
  33069. _this._renderTargets.reset();
  33070. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33071. _this._renderTargets.push(_this._reflectionTexture);
  33072. }
  33073. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33074. _this._renderTargets.push(_this._refractionTexture);
  33075. }
  33076. return _this._renderTargets;
  33077. };
  33078. return _this;
  33079. }
  33080. ;
  33081. ;
  33082. ;
  33083. ;
  33084. ;
  33085. ;
  33086. ;
  33087. ;
  33088. ;
  33089. ;
  33090. ;
  33091. ;
  33092. ;
  33093. ;
  33094. ;
  33095. ;
  33096. ;
  33097. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33098. /**
  33099. * Gets the image processing configuration used either in this material.
  33100. */
  33101. get: function () {
  33102. return this._imageProcessingConfiguration;
  33103. },
  33104. /**
  33105. * Sets the Default image processing configuration used either in the this material.
  33106. *
  33107. * If sets to null, the scene one is in use.
  33108. */
  33109. set: function (value) {
  33110. this._attachImageProcessingConfiguration(value);
  33111. // Ensure the effect will be rebuilt.
  33112. this._markAllSubMeshesAsTexturesDirty();
  33113. },
  33114. enumerable: true,
  33115. configurable: true
  33116. });
  33117. /**
  33118. * Attaches a new image processing configuration to the Standard Material.
  33119. * @param configuration
  33120. */
  33121. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33122. var _this = this;
  33123. if (configuration === this._imageProcessingConfiguration) {
  33124. return;
  33125. }
  33126. // Detaches observer.
  33127. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33128. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33129. }
  33130. // Pick the scene configuration if needed.
  33131. if (!configuration) {
  33132. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33133. }
  33134. else {
  33135. this._imageProcessingConfiguration = configuration;
  33136. }
  33137. // Attaches observer.
  33138. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33139. _this._markAllSubMeshesAsImageProcessingDirty();
  33140. });
  33141. };
  33142. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33143. /**
  33144. * Gets wether the color curves effect is enabled.
  33145. */
  33146. get: function () {
  33147. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33148. },
  33149. /**
  33150. * Sets wether the color curves effect is enabled.
  33151. */
  33152. set: function (value) {
  33153. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33154. },
  33155. enumerable: true,
  33156. configurable: true
  33157. });
  33158. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33159. /**
  33160. * Gets wether the color grading effect is enabled.
  33161. */
  33162. get: function () {
  33163. return this.imageProcessingConfiguration.colorGradingEnabled;
  33164. },
  33165. /**
  33166. * Gets wether the color grading effect is enabled.
  33167. */
  33168. set: function (value) {
  33169. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33170. },
  33171. enumerable: true,
  33172. configurable: true
  33173. });
  33174. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33175. /**
  33176. * Gets wether tonemapping is enabled or not.
  33177. */
  33178. get: function () {
  33179. return this._imageProcessingConfiguration.toneMappingEnabled;
  33180. },
  33181. /**
  33182. * Sets wether tonemapping is enabled or not
  33183. */
  33184. set: function (value) {
  33185. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33186. },
  33187. enumerable: true,
  33188. configurable: true
  33189. });
  33190. ;
  33191. ;
  33192. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33193. /**
  33194. * The camera exposure used on this material.
  33195. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33196. * This corresponds to a photographic exposure.
  33197. */
  33198. get: function () {
  33199. return this._imageProcessingConfiguration.exposure;
  33200. },
  33201. /**
  33202. * The camera exposure used on this material.
  33203. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33204. * This corresponds to a photographic exposure.
  33205. */
  33206. set: function (value) {
  33207. this._imageProcessingConfiguration.exposure = value;
  33208. },
  33209. enumerable: true,
  33210. configurable: true
  33211. });
  33212. ;
  33213. ;
  33214. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33215. /**
  33216. * Gets The camera contrast used on this material.
  33217. */
  33218. get: function () {
  33219. return this._imageProcessingConfiguration.contrast;
  33220. },
  33221. /**
  33222. * Sets The camera contrast used on this material.
  33223. */
  33224. set: function (value) {
  33225. this._imageProcessingConfiguration.contrast = value;
  33226. },
  33227. enumerable: true,
  33228. configurable: true
  33229. });
  33230. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33231. /**
  33232. * Gets the Color Grading 2D Lookup Texture.
  33233. */
  33234. get: function () {
  33235. return this._imageProcessingConfiguration.colorGradingTexture;
  33236. },
  33237. /**
  33238. * Sets the Color Grading 2D Lookup Texture.
  33239. */
  33240. set: function (value) {
  33241. this._imageProcessingConfiguration.colorGradingTexture = value;
  33242. },
  33243. enumerable: true,
  33244. configurable: true
  33245. });
  33246. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33247. /**
  33248. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33249. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33250. * 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;
  33251. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33252. */
  33253. get: function () {
  33254. return this._imageProcessingConfiguration.colorCurves;
  33255. },
  33256. /**
  33257. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33258. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33259. * 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;
  33260. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33261. */
  33262. set: function (value) {
  33263. this._imageProcessingConfiguration.colorCurves = value;
  33264. },
  33265. enumerable: true,
  33266. configurable: true
  33267. });
  33268. StandardMaterial.prototype.getClassName = function () {
  33269. return "StandardMaterial";
  33270. };
  33271. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33272. get: function () {
  33273. return this._useLogarithmicDepth;
  33274. },
  33275. set: function (value) {
  33276. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33277. this._markAllSubMeshesAsMiscDirty();
  33278. },
  33279. enumerable: true,
  33280. configurable: true
  33281. });
  33282. StandardMaterial.prototype.needAlphaBlending = function () {
  33283. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33284. };
  33285. StandardMaterial.prototype.needAlphaTesting = function () {
  33286. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33287. };
  33288. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33289. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33290. };
  33291. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33292. return this._diffuseTexture;
  33293. };
  33294. /**
  33295. * Child classes can use it to update shaders
  33296. */
  33297. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33298. if (useInstances === void 0) { useInstances = false; }
  33299. if (subMesh.effect && this.isFrozen) {
  33300. if (this._wasPreviouslyReady && subMesh.effect) {
  33301. return true;
  33302. }
  33303. }
  33304. if (!subMesh._materialDefines) {
  33305. subMesh._materialDefines = new StandardMaterialDefines();
  33306. }
  33307. var scene = this.getScene();
  33308. var defines = subMesh._materialDefines;
  33309. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33310. if (defines._renderId === scene.getRenderId()) {
  33311. return true;
  33312. }
  33313. }
  33314. var engine = scene.getEngine();
  33315. // Lights
  33316. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33317. // Textures
  33318. if (defines._areTexturesDirty) {
  33319. defines._needUVs = false;
  33320. defines.MAINUV1 = false;
  33321. defines.MAINUV2 = false;
  33322. if (scene.texturesEnabled) {
  33323. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33324. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33325. return false;
  33326. }
  33327. else {
  33328. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33329. }
  33330. }
  33331. else {
  33332. defines.DIFFUSE = false;
  33333. }
  33334. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33335. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33336. return false;
  33337. }
  33338. else {
  33339. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33340. }
  33341. }
  33342. else {
  33343. defines.AMBIENT = false;
  33344. }
  33345. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33346. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33347. return false;
  33348. }
  33349. else {
  33350. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33351. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33352. }
  33353. }
  33354. else {
  33355. defines.OPACITY = false;
  33356. }
  33357. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33358. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33359. return false;
  33360. }
  33361. else {
  33362. defines._needNormals = true;
  33363. defines.REFLECTION = true;
  33364. defines.ROUGHNESS = (this._roughness > 0);
  33365. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33366. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33367. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33368. switch (this._reflectionTexture.coordinatesMode) {
  33369. case BABYLON.Texture.CUBIC_MODE:
  33370. case BABYLON.Texture.INVCUBIC_MODE:
  33371. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33372. break;
  33373. case BABYLON.Texture.EXPLICIT_MODE:
  33374. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33375. break;
  33376. case BABYLON.Texture.PLANAR_MODE:
  33377. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33378. break;
  33379. case BABYLON.Texture.PROJECTION_MODE:
  33380. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33381. break;
  33382. case BABYLON.Texture.SKYBOX_MODE:
  33383. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33384. break;
  33385. case BABYLON.Texture.SPHERICAL_MODE:
  33386. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33387. break;
  33388. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33389. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33390. break;
  33391. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33392. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33393. break;
  33394. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33395. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33396. break;
  33397. }
  33398. }
  33399. }
  33400. else {
  33401. defines.REFLECTION = false;
  33402. }
  33403. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33404. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33405. return false;
  33406. }
  33407. else {
  33408. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33409. }
  33410. }
  33411. else {
  33412. defines.EMISSIVE = false;
  33413. }
  33414. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33415. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33416. return false;
  33417. }
  33418. else {
  33419. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33420. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33421. }
  33422. }
  33423. else {
  33424. defines.LIGHTMAP = false;
  33425. }
  33426. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33427. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33428. return false;
  33429. }
  33430. else {
  33431. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33432. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33433. }
  33434. }
  33435. else {
  33436. defines.SPECULAR = false;
  33437. }
  33438. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33439. // Bump texure can not be not blocking.
  33440. if (!this._bumpTexture.isReady()) {
  33441. return false;
  33442. }
  33443. else {
  33444. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33445. defines.PARALLAX = this._useParallax;
  33446. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33447. }
  33448. }
  33449. else {
  33450. defines.BUMP = false;
  33451. }
  33452. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33453. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33454. return false;
  33455. }
  33456. else {
  33457. defines._needUVs = true;
  33458. defines.REFRACTION = true;
  33459. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33460. }
  33461. }
  33462. else {
  33463. defines.REFRACTION = false;
  33464. }
  33465. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33466. }
  33467. else {
  33468. defines.DIFFUSE = false;
  33469. defines.AMBIENT = false;
  33470. defines.OPACITY = false;
  33471. defines.REFLECTION = false;
  33472. defines.EMISSIVE = false;
  33473. defines.LIGHTMAP = false;
  33474. defines.BUMP = false;
  33475. defines.REFRACTION = false;
  33476. }
  33477. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33478. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33479. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33480. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33481. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33482. }
  33483. if (defines._areImageProcessingDirty) {
  33484. if (!this._imageProcessingConfiguration.isReady()) {
  33485. return false;
  33486. }
  33487. this._imageProcessingConfiguration.prepareDefines(defines);
  33488. }
  33489. if (defines._areFresnelDirty) {
  33490. if (StandardMaterial.FresnelEnabled) {
  33491. // Fresnel
  33492. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33493. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33494. this._reflectionFresnelParameters) {
  33495. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33496. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33497. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33498. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33499. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33500. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33501. defines._needNormals = true;
  33502. defines.FRESNEL = true;
  33503. }
  33504. }
  33505. else {
  33506. defines.FRESNEL = false;
  33507. }
  33508. }
  33509. // Misc.
  33510. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33511. // Attribs
  33512. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33513. // Values that need to be evaluated on every frame
  33514. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33515. // Get correct effect
  33516. if (defines.isDirty) {
  33517. defines.markAsProcessed();
  33518. scene.resetCachedMaterial();
  33519. // Fallbacks
  33520. var fallbacks = new BABYLON.EffectFallbacks();
  33521. if (defines.REFLECTION) {
  33522. fallbacks.addFallback(0, "REFLECTION");
  33523. }
  33524. if (defines.SPECULAR) {
  33525. fallbacks.addFallback(0, "SPECULAR");
  33526. }
  33527. if (defines.BUMP) {
  33528. fallbacks.addFallback(0, "BUMP");
  33529. }
  33530. if (defines.PARALLAX) {
  33531. fallbacks.addFallback(1, "PARALLAX");
  33532. }
  33533. if (defines.PARALLAXOCCLUSION) {
  33534. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33535. }
  33536. if (defines.SPECULAROVERALPHA) {
  33537. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33538. }
  33539. if (defines.FOG) {
  33540. fallbacks.addFallback(1, "FOG");
  33541. }
  33542. if (defines.POINTSIZE) {
  33543. fallbacks.addFallback(0, "POINTSIZE");
  33544. }
  33545. if (defines.LOGARITHMICDEPTH) {
  33546. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33547. }
  33548. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33549. if (defines.SPECULARTERM) {
  33550. fallbacks.addFallback(0, "SPECULARTERM");
  33551. }
  33552. if (defines.DIFFUSEFRESNEL) {
  33553. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33554. }
  33555. if (defines.OPACITYFRESNEL) {
  33556. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33557. }
  33558. if (defines.REFLECTIONFRESNEL) {
  33559. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33560. }
  33561. if (defines.EMISSIVEFRESNEL) {
  33562. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33563. }
  33564. if (defines.FRESNEL) {
  33565. fallbacks.addFallback(4, "FRESNEL");
  33566. }
  33567. //Attributes
  33568. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33569. if (defines.NORMAL) {
  33570. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33571. }
  33572. if (defines.UV1) {
  33573. attribs.push(BABYLON.VertexBuffer.UVKind);
  33574. }
  33575. if (defines.UV2) {
  33576. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33577. }
  33578. if (defines.VERTEXCOLOR) {
  33579. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33580. }
  33581. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33582. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33583. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33584. var shaderName = "default";
  33585. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33586. "vFogInfos", "vFogColor", "pointSize",
  33587. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33588. "mBones",
  33589. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33590. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33591. "logarithmicDepthConstant", "vTangentSpaceParams"
  33592. ];
  33593. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33594. var uniformBuffers = ["Material", "Scene"];
  33595. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33596. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33597. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33598. uniformsNames: uniforms,
  33599. uniformBuffersNames: uniformBuffers,
  33600. samplers: samplers,
  33601. defines: defines,
  33602. maxSimultaneousLights: this._maxSimultaneousLights
  33603. });
  33604. if (this.customShaderNameResolve) {
  33605. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33606. }
  33607. var join = defines.toString();
  33608. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33609. attributes: attribs,
  33610. uniformsNames: uniforms,
  33611. uniformBuffersNames: uniformBuffers,
  33612. samplers: samplers,
  33613. defines: join,
  33614. fallbacks: fallbacks,
  33615. onCompiled: this.onCompiled,
  33616. onError: this.onError,
  33617. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33618. }, engine), defines);
  33619. this.buildUniformLayout();
  33620. }
  33621. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33622. return false;
  33623. }
  33624. defines._renderId = scene.getRenderId();
  33625. this._wasPreviouslyReady = true;
  33626. return true;
  33627. };
  33628. StandardMaterial.prototype.buildUniformLayout = function () {
  33629. // Order is important !
  33630. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33631. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33632. this._uniformBuffer.addUniform("opacityParts", 4);
  33633. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33634. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  33635. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  33636. this._uniformBuffer.addUniform("refractionRightColor", 4);
  33637. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  33638. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  33639. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  33640. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  33641. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  33642. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  33643. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  33644. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  33645. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  33646. this._uniformBuffer.addUniform("vBumpInfos", 3);
  33647. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  33648. this._uniformBuffer.addUniform("ambientMatrix", 16);
  33649. this._uniformBuffer.addUniform("opacityMatrix", 16);
  33650. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  33651. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  33652. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  33653. this._uniformBuffer.addUniform("specularMatrix", 16);
  33654. this._uniformBuffer.addUniform("bumpMatrix", 16);
  33655. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  33656. this._uniformBuffer.addUniform("refractionMatrix", 16);
  33657. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  33658. this._uniformBuffer.addUniform("vSpecularColor", 4);
  33659. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  33660. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  33661. this._uniformBuffer.addUniform("pointSize", 1);
  33662. this._uniformBuffer.create();
  33663. };
  33664. StandardMaterial.prototype.unbind = function () {
  33665. if (this._activeEffect) {
  33666. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  33667. this._activeEffect.setTexture("reflection2DSampler", null);
  33668. }
  33669. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  33670. this._activeEffect.setTexture("refraction2DSampler", null);
  33671. }
  33672. }
  33673. _super.prototype.unbind.call(this);
  33674. };
  33675. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  33676. var scene = this.getScene();
  33677. var defines = subMesh._materialDefines;
  33678. if (!defines) {
  33679. return;
  33680. }
  33681. var effect = subMesh.effect;
  33682. if (!effect) {
  33683. return;
  33684. }
  33685. this._activeEffect = effect;
  33686. // Matrices
  33687. this.bindOnlyWorldMatrix(world);
  33688. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  33689. // Bones
  33690. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  33691. if (mustRebind) {
  33692. this._uniformBuffer.bindToEffect(effect, "Material");
  33693. this.bindViewProjection(effect);
  33694. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  33695. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  33696. // Fresnel
  33697. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  33698. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  33699. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  33700. }
  33701. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  33702. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  33703. }
  33704. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  33705. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  33706. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  33707. }
  33708. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  33709. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  33710. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  33711. }
  33712. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  33713. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  33714. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  33715. }
  33716. }
  33717. // Textures
  33718. if (scene.texturesEnabled) {
  33719. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33720. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  33721. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  33722. }
  33723. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33724. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  33725. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  33726. }
  33727. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33728. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  33729. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  33730. }
  33731. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33732. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  33733. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  33734. }
  33735. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33736. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  33737. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  33738. }
  33739. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33740. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  33741. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  33742. }
  33743. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33744. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  33745. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  33746. }
  33747. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33748. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  33749. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  33750. if (scene._mirroredCameraPosition) {
  33751. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  33752. }
  33753. else {
  33754. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  33755. }
  33756. }
  33757. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33758. var depth = 1.0;
  33759. if (!this._refractionTexture.isCube) {
  33760. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  33761. if (this._refractionTexture.depth) {
  33762. depth = this._refractionTexture.depth;
  33763. }
  33764. }
  33765. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  33766. }
  33767. }
  33768. // Point size
  33769. if (this.pointsCloud) {
  33770. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  33771. }
  33772. if (defines.SPECULARTERM) {
  33773. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  33774. }
  33775. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  33776. // Diffuse
  33777. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  33778. }
  33779. // Textures
  33780. if (scene.texturesEnabled) {
  33781. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33782. effect.setTexture("diffuseSampler", this._diffuseTexture);
  33783. }
  33784. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33785. effect.setTexture("ambientSampler", this._ambientTexture);
  33786. }
  33787. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33788. effect.setTexture("opacitySampler", this._opacityTexture);
  33789. }
  33790. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33791. if (this._reflectionTexture.isCube) {
  33792. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  33793. }
  33794. else {
  33795. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  33796. }
  33797. }
  33798. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33799. effect.setTexture("emissiveSampler", this._emissiveTexture);
  33800. }
  33801. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33802. effect.setTexture("lightmapSampler", this._lightmapTexture);
  33803. }
  33804. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33805. effect.setTexture("specularSampler", this._specularTexture);
  33806. }
  33807. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33808. effect.setTexture("bumpSampler", this._bumpTexture);
  33809. }
  33810. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33811. var depth = 1.0;
  33812. if (this._refractionTexture.isCube) {
  33813. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  33814. }
  33815. else {
  33816. effect.setTexture("refraction2DSampler", this._refractionTexture);
  33817. }
  33818. }
  33819. }
  33820. // Clip plane
  33821. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  33822. // Colors
  33823. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  33824. if (scene.activeCamera) {
  33825. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  33826. }
  33827. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  33828. }
  33829. if (mustRebind || !this.isFrozen) {
  33830. // Lights
  33831. if (scene.lightsEnabled && !this._disableLighting) {
  33832. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  33833. }
  33834. // View
  33835. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  33836. this.bindView(effect);
  33837. }
  33838. // Fog
  33839. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  33840. // Morph targets
  33841. if (defines.NUM_MORPH_INFLUENCERS) {
  33842. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  33843. }
  33844. // Log. depth
  33845. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  33846. // image processing
  33847. this._imageProcessingConfiguration.bind(this._activeEffect);
  33848. }
  33849. this._uniformBuffer.update();
  33850. this._afterBind(mesh, this._activeEffect);
  33851. };
  33852. StandardMaterial.prototype.getAnimatables = function () {
  33853. var results = [];
  33854. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  33855. results.push(this._diffuseTexture);
  33856. }
  33857. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  33858. results.push(this._ambientTexture);
  33859. }
  33860. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  33861. results.push(this._opacityTexture);
  33862. }
  33863. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  33864. results.push(this._reflectionTexture);
  33865. }
  33866. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  33867. results.push(this._emissiveTexture);
  33868. }
  33869. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  33870. results.push(this._specularTexture);
  33871. }
  33872. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  33873. results.push(this._bumpTexture);
  33874. }
  33875. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  33876. results.push(this._lightmapTexture);
  33877. }
  33878. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  33879. results.push(this._refractionTexture);
  33880. }
  33881. return results;
  33882. };
  33883. StandardMaterial.prototype.getActiveTextures = function () {
  33884. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33885. if (this._diffuseTexture) {
  33886. activeTextures.push(this._diffuseTexture);
  33887. }
  33888. if (this._ambientTexture) {
  33889. activeTextures.push(this._ambientTexture);
  33890. }
  33891. if (this._opacityTexture) {
  33892. activeTextures.push(this._opacityTexture);
  33893. }
  33894. if (this._reflectionTexture) {
  33895. activeTextures.push(this._reflectionTexture);
  33896. }
  33897. if (this._emissiveTexture) {
  33898. activeTextures.push(this._emissiveTexture);
  33899. }
  33900. if (this._specularTexture) {
  33901. activeTextures.push(this._specularTexture);
  33902. }
  33903. if (this._bumpTexture) {
  33904. activeTextures.push(this._bumpTexture);
  33905. }
  33906. if (this._lightmapTexture) {
  33907. activeTextures.push(this._lightmapTexture);
  33908. }
  33909. if (this._refractionTexture) {
  33910. activeTextures.push(this._refractionTexture);
  33911. }
  33912. return activeTextures;
  33913. };
  33914. StandardMaterial.prototype.hasTexture = function (texture) {
  33915. if (_super.prototype.hasTexture.call(this, texture)) {
  33916. return true;
  33917. }
  33918. if (this._diffuseTexture === texture) {
  33919. return true;
  33920. }
  33921. if (this._ambientTexture === texture) {
  33922. return true;
  33923. }
  33924. if (this._opacityTexture === texture) {
  33925. return true;
  33926. }
  33927. if (this._reflectionTexture === texture) {
  33928. return true;
  33929. }
  33930. if (this._emissiveTexture === texture) {
  33931. return true;
  33932. }
  33933. if (this._specularTexture === texture) {
  33934. return true;
  33935. }
  33936. if (this._bumpTexture === texture) {
  33937. return true;
  33938. }
  33939. if (this._lightmapTexture === texture) {
  33940. return true;
  33941. }
  33942. if (this._refractionTexture === texture) {
  33943. return true;
  33944. }
  33945. return false;
  33946. };
  33947. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  33948. if (forceDisposeTextures) {
  33949. if (this._diffuseTexture) {
  33950. this._diffuseTexture.dispose();
  33951. }
  33952. if (this._ambientTexture) {
  33953. this._ambientTexture.dispose();
  33954. }
  33955. if (this._opacityTexture) {
  33956. this._opacityTexture.dispose();
  33957. }
  33958. if (this._reflectionTexture) {
  33959. this._reflectionTexture.dispose();
  33960. }
  33961. if (this._emissiveTexture) {
  33962. this._emissiveTexture.dispose();
  33963. }
  33964. if (this._specularTexture) {
  33965. this._specularTexture.dispose();
  33966. }
  33967. if (this._bumpTexture) {
  33968. this._bumpTexture.dispose();
  33969. }
  33970. if (this._lightmapTexture) {
  33971. this._lightmapTexture.dispose();
  33972. }
  33973. if (this._refractionTexture) {
  33974. this._refractionTexture.dispose();
  33975. }
  33976. }
  33977. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33978. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33979. }
  33980. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  33981. };
  33982. StandardMaterial.prototype.clone = function (name) {
  33983. var _this = this;
  33984. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  33985. result.name = name;
  33986. result.id = name;
  33987. return result;
  33988. };
  33989. StandardMaterial.prototype.serialize = function () {
  33990. return BABYLON.SerializationHelper.Serialize(this);
  33991. };
  33992. // Statics
  33993. StandardMaterial.Parse = function (source, scene, rootUrl) {
  33994. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  33995. };
  33996. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  33997. get: function () {
  33998. return StandardMaterial._DiffuseTextureEnabled;
  33999. },
  34000. set: function (value) {
  34001. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34002. return;
  34003. }
  34004. StandardMaterial._DiffuseTextureEnabled = value;
  34005. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34006. },
  34007. enumerable: true,
  34008. configurable: true
  34009. });
  34010. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34011. get: function () {
  34012. return StandardMaterial._AmbientTextureEnabled;
  34013. },
  34014. set: function (value) {
  34015. if (StandardMaterial._AmbientTextureEnabled === value) {
  34016. return;
  34017. }
  34018. StandardMaterial._AmbientTextureEnabled = value;
  34019. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34020. },
  34021. enumerable: true,
  34022. configurable: true
  34023. });
  34024. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34025. get: function () {
  34026. return StandardMaterial._OpacityTextureEnabled;
  34027. },
  34028. set: function (value) {
  34029. if (StandardMaterial._OpacityTextureEnabled === value) {
  34030. return;
  34031. }
  34032. StandardMaterial._OpacityTextureEnabled = value;
  34033. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34034. },
  34035. enumerable: true,
  34036. configurable: true
  34037. });
  34038. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34039. get: function () {
  34040. return StandardMaterial._ReflectionTextureEnabled;
  34041. },
  34042. set: function (value) {
  34043. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34044. return;
  34045. }
  34046. StandardMaterial._ReflectionTextureEnabled = value;
  34047. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34048. },
  34049. enumerable: true,
  34050. configurable: true
  34051. });
  34052. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34053. get: function () {
  34054. return StandardMaterial._EmissiveTextureEnabled;
  34055. },
  34056. set: function (value) {
  34057. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34058. return;
  34059. }
  34060. StandardMaterial._EmissiveTextureEnabled = value;
  34061. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34062. },
  34063. enumerable: true,
  34064. configurable: true
  34065. });
  34066. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34067. get: function () {
  34068. return StandardMaterial._SpecularTextureEnabled;
  34069. },
  34070. set: function (value) {
  34071. if (StandardMaterial._SpecularTextureEnabled === value) {
  34072. return;
  34073. }
  34074. StandardMaterial._SpecularTextureEnabled = value;
  34075. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34076. },
  34077. enumerable: true,
  34078. configurable: true
  34079. });
  34080. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34081. get: function () {
  34082. return StandardMaterial._BumpTextureEnabled;
  34083. },
  34084. set: function (value) {
  34085. if (StandardMaterial._BumpTextureEnabled === value) {
  34086. return;
  34087. }
  34088. StandardMaterial._BumpTextureEnabled = value;
  34089. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34090. },
  34091. enumerable: true,
  34092. configurable: true
  34093. });
  34094. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34095. get: function () {
  34096. return StandardMaterial._LightmapTextureEnabled;
  34097. },
  34098. set: function (value) {
  34099. if (StandardMaterial._LightmapTextureEnabled === value) {
  34100. return;
  34101. }
  34102. StandardMaterial._LightmapTextureEnabled = value;
  34103. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34104. },
  34105. enumerable: true,
  34106. configurable: true
  34107. });
  34108. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34109. get: function () {
  34110. return StandardMaterial._RefractionTextureEnabled;
  34111. },
  34112. set: function (value) {
  34113. if (StandardMaterial._RefractionTextureEnabled === value) {
  34114. return;
  34115. }
  34116. StandardMaterial._RefractionTextureEnabled = value;
  34117. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34118. },
  34119. enumerable: true,
  34120. configurable: true
  34121. });
  34122. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34123. get: function () {
  34124. return StandardMaterial._ColorGradingTextureEnabled;
  34125. },
  34126. set: function (value) {
  34127. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34128. return;
  34129. }
  34130. StandardMaterial._ColorGradingTextureEnabled = value;
  34131. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34132. },
  34133. enumerable: true,
  34134. configurable: true
  34135. });
  34136. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34137. get: function () {
  34138. return StandardMaterial._FresnelEnabled;
  34139. },
  34140. set: function (value) {
  34141. if (StandardMaterial._FresnelEnabled === value) {
  34142. return;
  34143. }
  34144. StandardMaterial._FresnelEnabled = value;
  34145. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34146. },
  34147. enumerable: true,
  34148. configurable: true
  34149. });
  34150. // Flags used to enable or disable a type of texture for all Standard Materials
  34151. StandardMaterial._DiffuseTextureEnabled = true;
  34152. StandardMaterial._AmbientTextureEnabled = true;
  34153. StandardMaterial._OpacityTextureEnabled = true;
  34154. StandardMaterial._ReflectionTextureEnabled = true;
  34155. StandardMaterial._EmissiveTextureEnabled = true;
  34156. StandardMaterial._SpecularTextureEnabled = true;
  34157. StandardMaterial._BumpTextureEnabled = true;
  34158. StandardMaterial._LightmapTextureEnabled = true;
  34159. StandardMaterial._RefractionTextureEnabled = true;
  34160. StandardMaterial._ColorGradingTextureEnabled = true;
  34161. StandardMaterial._FresnelEnabled = true;
  34162. __decorate([
  34163. BABYLON.serializeAsTexture("diffuseTexture")
  34164. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34165. __decorate([
  34166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34167. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34168. __decorate([
  34169. BABYLON.serializeAsTexture("ambientTexture")
  34170. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34171. __decorate([
  34172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34173. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34174. __decorate([
  34175. BABYLON.serializeAsTexture("opacityTexture")
  34176. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34177. __decorate([
  34178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34179. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34180. __decorate([
  34181. BABYLON.serializeAsTexture("reflectionTexture")
  34182. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34183. __decorate([
  34184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34185. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34186. __decorate([
  34187. BABYLON.serializeAsTexture("emissiveTexture")
  34188. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34189. __decorate([
  34190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34191. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34192. __decorate([
  34193. BABYLON.serializeAsTexture("specularTexture")
  34194. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34195. __decorate([
  34196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34197. ], StandardMaterial.prototype, "specularTexture", void 0);
  34198. __decorate([
  34199. BABYLON.serializeAsTexture("bumpTexture")
  34200. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34201. __decorate([
  34202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34203. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34204. __decorate([
  34205. BABYLON.serializeAsTexture("lightmapTexture")
  34206. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34207. __decorate([
  34208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34209. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34210. __decorate([
  34211. BABYLON.serializeAsTexture("refractionTexture")
  34212. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34213. __decorate([
  34214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34215. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34216. __decorate([
  34217. BABYLON.serializeAsColor3("ambient")
  34218. ], StandardMaterial.prototype, "ambientColor", void 0);
  34219. __decorate([
  34220. BABYLON.serializeAsColor3("diffuse")
  34221. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34222. __decorate([
  34223. BABYLON.serializeAsColor3("specular")
  34224. ], StandardMaterial.prototype, "specularColor", void 0);
  34225. __decorate([
  34226. BABYLON.serializeAsColor3("emissive")
  34227. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34228. __decorate([
  34229. BABYLON.serialize()
  34230. ], StandardMaterial.prototype, "specularPower", void 0);
  34231. __decorate([
  34232. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34233. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34234. __decorate([
  34235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34236. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34237. __decorate([
  34238. BABYLON.serialize("useEmissiveAsIllumination")
  34239. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34240. __decorate([
  34241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34242. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34243. __decorate([
  34244. BABYLON.serialize("linkEmissiveWithDiffuse")
  34245. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34246. __decorate([
  34247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34248. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34249. __decorate([
  34250. BABYLON.serialize("useSpecularOverAlpha")
  34251. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34252. __decorate([
  34253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34254. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34255. __decorate([
  34256. BABYLON.serialize("useReflectionOverAlpha")
  34257. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34258. __decorate([
  34259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34260. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34261. __decorate([
  34262. BABYLON.serialize("disableLighting")
  34263. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34264. __decorate([
  34265. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34266. ], StandardMaterial.prototype, "disableLighting", void 0);
  34267. __decorate([
  34268. BABYLON.serialize("useParallax")
  34269. ], StandardMaterial.prototype, "_useParallax", void 0);
  34270. __decorate([
  34271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34272. ], StandardMaterial.prototype, "useParallax", void 0);
  34273. __decorate([
  34274. BABYLON.serialize("useParallaxOcclusion")
  34275. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34276. __decorate([
  34277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34278. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34279. __decorate([
  34280. BABYLON.serialize()
  34281. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34282. __decorate([
  34283. BABYLON.serialize("roughness")
  34284. ], StandardMaterial.prototype, "_roughness", void 0);
  34285. __decorate([
  34286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34287. ], StandardMaterial.prototype, "roughness", void 0);
  34288. __decorate([
  34289. BABYLON.serialize()
  34290. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34291. __decorate([
  34292. BABYLON.serialize()
  34293. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34294. __decorate([
  34295. BABYLON.serialize("useLightmapAsShadowmap")
  34296. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34297. __decorate([
  34298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34299. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34300. __decorate([
  34301. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34302. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34303. __decorate([
  34304. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34305. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34306. __decorate([
  34307. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34308. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34309. __decorate([
  34310. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34311. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34312. __decorate([
  34313. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34314. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34315. __decorate([
  34316. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34317. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34318. __decorate([
  34319. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34320. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34321. __decorate([
  34322. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34323. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34324. __decorate([
  34325. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34326. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34327. __decorate([
  34328. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34329. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34330. __decorate([
  34331. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34332. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34333. __decorate([
  34334. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34335. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34336. __decorate([
  34337. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34338. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34339. __decorate([
  34340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34341. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34342. __decorate([
  34343. BABYLON.serialize("maxSimultaneousLights")
  34344. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34345. __decorate([
  34346. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34347. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34348. __decorate([
  34349. BABYLON.serialize("invertNormalMapX")
  34350. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34351. __decorate([
  34352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34353. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34354. __decorate([
  34355. BABYLON.serialize("invertNormalMapY")
  34356. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34357. __decorate([
  34358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34359. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34360. __decorate([
  34361. BABYLON.serialize("twoSidedLighting")
  34362. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34363. __decorate([
  34364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34365. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34366. __decorate([
  34367. BABYLON.serialize()
  34368. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34369. return StandardMaterial;
  34370. }(BABYLON.PushMaterial));
  34371. BABYLON.StandardMaterial = StandardMaterial;
  34372. })(BABYLON || (BABYLON = {}));
  34373. //# sourceMappingURL=babylon.standardMaterial.js.map
  34374. var BABYLON;
  34375. (function (BABYLON) {
  34376. var PBRMaterialDefines = /** @class */ (function (_super) {
  34377. __extends(PBRMaterialDefines, _super);
  34378. function PBRMaterialDefines() {
  34379. var _this = _super.call(this) || this;
  34380. _this.PBR = true;
  34381. _this.MAINUV1 = false;
  34382. _this.MAINUV2 = false;
  34383. _this.UV1 = false;
  34384. _this.UV2 = false;
  34385. _this.ALBEDO = false;
  34386. _this.ALBEDODIRECTUV = 0;
  34387. _this.VERTEXCOLOR = false;
  34388. _this.AMBIENT = false;
  34389. _this.AMBIENTDIRECTUV = 0;
  34390. _this.AMBIENTINGRAYSCALE = false;
  34391. _this.OPACITY = false;
  34392. _this.VERTEXALPHA = false;
  34393. _this.OPACITYDIRECTUV = 0;
  34394. _this.OPACITYRGB = false;
  34395. _this.ALPHATEST = false;
  34396. _this.DEPTHPREPASS = false;
  34397. _this.ALPHABLEND = false;
  34398. _this.ALPHAFROMALBEDO = false;
  34399. _this.ALPHATESTVALUE = 0.5;
  34400. _this.SPECULAROVERALPHA = false;
  34401. _this.RADIANCEOVERALPHA = false;
  34402. _this.ALPHAFRESNEL = false;
  34403. _this.PREMULTIPLYALPHA = false;
  34404. _this.EMISSIVE = false;
  34405. _this.EMISSIVEDIRECTUV = 0;
  34406. _this.REFLECTIVITY = false;
  34407. _this.REFLECTIVITYDIRECTUV = 0;
  34408. _this.SPECULARTERM = false;
  34409. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34410. _this.MICROSURFACEAUTOMATIC = false;
  34411. _this.LODBASEDMICROSFURACE = false;
  34412. _this.MICROSURFACEMAP = false;
  34413. _this.MICROSURFACEMAPDIRECTUV = 0;
  34414. _this.METALLICWORKFLOW = false;
  34415. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34416. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34417. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34418. _this.AOSTOREINMETALMAPRED = false;
  34419. _this.ENVIRONMENTBRDF = false;
  34420. _this.NORMAL = false;
  34421. _this.TANGENT = false;
  34422. _this.BUMP = false;
  34423. _this.BUMPDIRECTUV = 0;
  34424. _this.PARALLAX = false;
  34425. _this.PARALLAXOCCLUSION = false;
  34426. _this.NORMALXYSCALE = true;
  34427. _this.LIGHTMAP = false;
  34428. _this.LIGHTMAPDIRECTUV = 0;
  34429. _this.USELIGHTMAPASSHADOWMAP = false;
  34430. _this.REFLECTION = false;
  34431. _this.REFLECTIONMAP_3D = false;
  34432. _this.REFLECTIONMAP_SPHERICAL = false;
  34433. _this.REFLECTIONMAP_PLANAR = false;
  34434. _this.REFLECTIONMAP_CUBIC = false;
  34435. _this.REFLECTIONMAP_PROJECTION = false;
  34436. _this.REFLECTIONMAP_SKYBOX = false;
  34437. _this.REFLECTIONMAP_EXPLICIT = false;
  34438. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34439. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34440. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34441. _this.INVERTCUBICMAP = false;
  34442. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34443. _this.USESPHERICALINFRAGMENT = false;
  34444. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34445. _this.LODINREFLECTIONALPHA = false;
  34446. _this.GAMMAREFLECTION = false;
  34447. _this.REFRACTION = false;
  34448. _this.REFRACTIONMAP_3D = false;
  34449. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34450. _this.LODINREFRACTIONALPHA = false;
  34451. _this.GAMMAREFRACTION = false;
  34452. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34453. _this.INSTANCES = false;
  34454. _this.NUM_BONE_INFLUENCERS = 0;
  34455. _this.BonesPerMesh = 0;
  34456. _this.NONUNIFORMSCALING = false;
  34457. _this.MORPHTARGETS = false;
  34458. _this.MORPHTARGETS_NORMAL = false;
  34459. _this.MORPHTARGETS_TANGENT = false;
  34460. _this.NUM_MORPH_INFLUENCERS = 0;
  34461. _this.IMAGEPROCESSING = false;
  34462. _this.VIGNETTE = false;
  34463. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34464. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34465. _this.TONEMAPPING = false;
  34466. _this.CONTRAST = false;
  34467. _this.COLORCURVES = false;
  34468. _this.COLORGRADING = false;
  34469. _this.COLORGRADING3D = false;
  34470. _this.SAMPLER3DGREENDEPTH = false;
  34471. _this.SAMPLER3DBGRMAP = false;
  34472. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34473. _this.EXPOSURE = false;
  34474. _this.USEPHYSICALLIGHTFALLOFF = false;
  34475. _this.TWOSIDEDLIGHTING = false;
  34476. _this.SHADOWFLOAT = false;
  34477. _this.CLIPPLANE = false;
  34478. _this.POINTSIZE = false;
  34479. _this.FOG = false;
  34480. _this.LOGARITHMICDEPTH = false;
  34481. _this.FORCENORMALFORWARD = false;
  34482. _this.rebuild();
  34483. return _this;
  34484. }
  34485. PBRMaterialDefines.prototype.reset = function () {
  34486. _super.prototype.reset.call(this);
  34487. this.ALPHATESTVALUE = 0.5;
  34488. this.PBR = true;
  34489. };
  34490. return PBRMaterialDefines;
  34491. }(BABYLON.MaterialDefines));
  34492. /**
  34493. * The Physically based material base class of BJS.
  34494. *
  34495. * This offers the main features of a standard PBR material.
  34496. * For more information, please refer to the documentation :
  34497. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34498. */
  34499. var PBRBaseMaterial = /** @class */ (function (_super) {
  34500. __extends(PBRBaseMaterial, _super);
  34501. /**
  34502. * Instantiates a new PBRMaterial instance.
  34503. *
  34504. * @param name The material name
  34505. * @param scene The scene the material will be use in.
  34506. */
  34507. function PBRBaseMaterial(name, scene) {
  34508. var _this = _super.call(this, name, scene) || this;
  34509. /**
  34510. * Intensity of the direct lights e.g. the four lights available in your scene.
  34511. * This impacts both the direct diffuse and specular highlights.
  34512. */
  34513. _this._directIntensity = 1.0;
  34514. /**
  34515. * Intensity of the emissive part of the material.
  34516. * This helps controlling the emissive effect without modifying the emissive color.
  34517. */
  34518. _this._emissiveIntensity = 1.0;
  34519. /**
  34520. * Intensity of the environment e.g. how much the environment will light the object
  34521. * either through harmonics for rough material or through the refelction for shiny ones.
  34522. */
  34523. _this._environmentIntensity = 1.0;
  34524. /**
  34525. * This is a special control allowing the reduction of the specular highlights coming from the
  34526. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34527. */
  34528. _this._specularIntensity = 1.0;
  34529. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34530. /**
  34531. * Debug Control allowing disabling the bump map on this material.
  34532. */
  34533. _this._disableBumpMap = false;
  34534. /**
  34535. * AKA Occlusion Texture Intensity in other nomenclature.
  34536. */
  34537. _this._ambientTextureStrength = 1.0;
  34538. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34539. /**
  34540. * AKA Diffuse Color in other nomenclature.
  34541. */
  34542. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34543. /**
  34544. * AKA Specular Color in other nomenclature.
  34545. */
  34546. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34547. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34548. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34549. /**
  34550. * AKA Glossiness in other nomenclature.
  34551. */
  34552. _this._microSurface = 0.9;
  34553. /**
  34554. * source material index of refraction (IOR)' / 'destination material IOR.
  34555. */
  34556. _this._indexOfRefraction = 0.66;
  34557. /**
  34558. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34559. */
  34560. _this._invertRefractionY = false;
  34561. /**
  34562. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34563. * Materials half opaque for instance using refraction could benefit from this control.
  34564. */
  34565. _this._linkRefractionWithTransparency = false;
  34566. _this._useLightmapAsShadowmap = false;
  34567. /**
  34568. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34569. */
  34570. _this._useAlphaFromAlbedoTexture = false;
  34571. /**
  34572. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34573. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34574. */
  34575. _this._useSpecularOverAlpha = true;
  34576. /**
  34577. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34578. */
  34579. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34580. /**
  34581. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34582. */
  34583. _this._useRoughnessFromMetallicTextureAlpha = true;
  34584. /**
  34585. * Specifies if the metallic texture contains the roughness information in its green channel.
  34586. */
  34587. _this._useRoughnessFromMetallicTextureGreen = false;
  34588. /**
  34589. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34590. */
  34591. _this._useMetallnessFromMetallicTextureBlue = false;
  34592. /**
  34593. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34594. */
  34595. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34596. /**
  34597. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34598. */
  34599. _this._useAmbientInGrayScale = false;
  34600. /**
  34601. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34602. * The material will try to infer what glossiness each pixel should be.
  34603. */
  34604. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34605. /**
  34606. * BJS is using an harcoded light falloff based on a manually sets up range.
  34607. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34608. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34609. */
  34610. _this._usePhysicalLightFalloff = true;
  34611. /**
  34612. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34613. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34614. */
  34615. _this._useRadianceOverAlpha = true;
  34616. /**
  34617. * Allows using the bump map in parallax mode.
  34618. */
  34619. _this._useParallax = false;
  34620. /**
  34621. * Allows using the bump map in parallax occlusion mode.
  34622. */
  34623. _this._useParallaxOcclusion = false;
  34624. /**
  34625. * Controls the scale bias of the parallax mode.
  34626. */
  34627. _this._parallaxScaleBias = 0.05;
  34628. /**
  34629. * If sets to true, disables all the lights affecting the material.
  34630. */
  34631. _this._disableLighting = false;
  34632. /**
  34633. * Number of Simultaneous lights allowed on the material.
  34634. */
  34635. _this._maxSimultaneousLights = 4;
  34636. /**
  34637. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  34638. */
  34639. _this._invertNormalMapX = false;
  34640. /**
  34641. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  34642. */
  34643. _this._invertNormalMapY = false;
  34644. /**
  34645. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34646. */
  34647. _this._twoSidedLighting = false;
  34648. /**
  34649. * Defines the alpha limits in alpha test mode.
  34650. */
  34651. _this._alphaCutOff = 0.4;
  34652. /**
  34653. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34654. */
  34655. _this._forceAlphaTest = false;
  34656. /**
  34657. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34658. * And/Or occlude the blended part.
  34659. */
  34660. _this._useAlphaFresnel = false;
  34661. /**
  34662. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  34663. * from cos thetav and roughness:
  34664. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  34665. */
  34666. _this._environmentBRDFTexture = null;
  34667. /**
  34668. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34669. */
  34670. _this._forceIrradianceInFragment = false;
  34671. /**
  34672. * Force normal to face away from face.
  34673. * (Temporary internal fix to remove before 3.1)
  34674. */
  34675. _this._forceNormalForward = false;
  34676. _this._renderTargets = new BABYLON.SmartArray(16);
  34677. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34678. // Setup the default processing configuration to the scene.
  34679. _this._attachImageProcessingConfiguration(null);
  34680. _this.getRenderTargetTextures = function () {
  34681. _this._renderTargets.reset();
  34682. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34683. _this._renderTargets.push(_this._reflectionTexture);
  34684. }
  34685. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34686. _this._renderTargets.push(_this._refractionTexture);
  34687. }
  34688. return _this._renderTargets;
  34689. };
  34690. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  34691. return _this;
  34692. }
  34693. /**
  34694. * Attaches a new image processing configuration to the PBR Material.
  34695. * @param configuration
  34696. */
  34697. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34698. var _this = this;
  34699. if (configuration === this._imageProcessingConfiguration) {
  34700. return;
  34701. }
  34702. // Detaches observer.
  34703. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34704. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34705. }
  34706. // Pick the scene configuration if needed.
  34707. if (!configuration) {
  34708. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34709. }
  34710. else {
  34711. this._imageProcessingConfiguration = configuration;
  34712. }
  34713. // Attaches observer.
  34714. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34715. _this._markAllSubMeshesAsImageProcessingDirty();
  34716. });
  34717. };
  34718. PBRBaseMaterial.prototype.getClassName = function () {
  34719. return "PBRBaseMaterial";
  34720. };
  34721. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34722. get: function () {
  34723. return this._useLogarithmicDepth;
  34724. },
  34725. set: function (value) {
  34726. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34727. },
  34728. enumerable: true,
  34729. configurable: true
  34730. });
  34731. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34732. if (this._linkRefractionWithTransparency) {
  34733. return false;
  34734. }
  34735. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  34736. };
  34737. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34738. if (this._forceAlphaTest) {
  34739. return true;
  34740. }
  34741. if (this._linkRefractionWithTransparency) {
  34742. return false;
  34743. }
  34744. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34745. };
  34746. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34747. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34748. };
  34749. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34750. return this._albedoTexture;
  34751. };
  34752. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34753. var _this = this;
  34754. if (subMesh.effect && this.isFrozen) {
  34755. if (this._wasPreviouslyReady) {
  34756. return true;
  34757. }
  34758. }
  34759. if (!subMesh._materialDefines) {
  34760. subMesh._materialDefines = new PBRMaterialDefines();
  34761. }
  34762. var scene = this.getScene();
  34763. var defines = subMesh._materialDefines;
  34764. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34765. if (defines._renderId === scene.getRenderId()) {
  34766. return true;
  34767. }
  34768. }
  34769. var engine = scene.getEngine();
  34770. // Lights
  34771. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34772. defines._needNormals = true;
  34773. // Textures
  34774. if (defines._areTexturesDirty) {
  34775. defines._needUVs = false;
  34776. if (scene.texturesEnabled) {
  34777. if (scene.getEngine().getCaps().textureLOD) {
  34778. defines.LODBASEDMICROSFURACE = true;
  34779. }
  34780. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34781. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  34782. return false;
  34783. }
  34784. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  34785. }
  34786. else {
  34787. defines.ALBEDO = false;
  34788. }
  34789. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34790. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34791. return false;
  34792. }
  34793. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34794. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  34795. }
  34796. else {
  34797. defines.AMBIENT = false;
  34798. }
  34799. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34800. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34801. return false;
  34802. }
  34803. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34804. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34805. }
  34806. else {
  34807. defines.OPACITY = false;
  34808. }
  34809. var reflectionTexture = this._getReflectionTexture();
  34810. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34811. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34812. return false;
  34813. }
  34814. defines.REFLECTION = true;
  34815. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  34816. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  34817. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34818. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34819. defines.INVERTCUBICMAP = true;
  34820. }
  34821. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  34822. switch (reflectionTexture.coordinatesMode) {
  34823. case BABYLON.Texture.CUBIC_MODE:
  34824. case BABYLON.Texture.INVCUBIC_MODE:
  34825. defines.REFLECTIONMAP_CUBIC = true;
  34826. break;
  34827. case BABYLON.Texture.EXPLICIT_MODE:
  34828. defines.REFLECTIONMAP_EXPLICIT = true;
  34829. break;
  34830. case BABYLON.Texture.PLANAR_MODE:
  34831. defines.REFLECTIONMAP_PLANAR = true;
  34832. break;
  34833. case BABYLON.Texture.PROJECTION_MODE:
  34834. defines.REFLECTIONMAP_PROJECTION = true;
  34835. break;
  34836. case BABYLON.Texture.SKYBOX_MODE:
  34837. defines.REFLECTIONMAP_SKYBOX = true;
  34838. break;
  34839. case BABYLON.Texture.SPHERICAL_MODE:
  34840. defines.REFLECTIONMAP_SPHERICAL = true;
  34841. break;
  34842. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34843. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  34844. break;
  34845. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34846. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  34847. break;
  34848. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34849. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  34850. break;
  34851. }
  34852. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  34853. if (reflectionTexture.sphericalPolynomial) {
  34854. defines.USESPHERICALFROMREFLECTIONMAP = true;
  34855. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  34856. defines.USESPHERICALINFRAGMENT = true;
  34857. }
  34858. }
  34859. }
  34860. }
  34861. else {
  34862. defines.REFLECTION = false;
  34863. defines.REFLECTIONMAP_3D = false;
  34864. defines.REFLECTIONMAP_SPHERICAL = false;
  34865. defines.REFLECTIONMAP_PLANAR = false;
  34866. defines.REFLECTIONMAP_CUBIC = false;
  34867. defines.REFLECTIONMAP_PROJECTION = false;
  34868. defines.REFLECTIONMAP_SKYBOX = false;
  34869. defines.REFLECTIONMAP_EXPLICIT = false;
  34870. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34871. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34872. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34873. defines.INVERTCUBICMAP = false;
  34874. defines.USESPHERICALFROMREFLECTIONMAP = false;
  34875. defines.USESPHERICALINFRAGMENT = false;
  34876. defines.REFLECTIONMAP_OPPOSITEZ = false;
  34877. defines.LODINREFLECTIONALPHA = false;
  34878. defines.GAMMAREFLECTION = false;
  34879. }
  34880. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34881. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34882. return false;
  34883. }
  34884. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34885. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34886. }
  34887. else {
  34888. defines.LIGHTMAP = false;
  34889. }
  34890. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34891. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34892. return false;
  34893. }
  34894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34895. }
  34896. else {
  34897. defines.EMISSIVE = false;
  34898. }
  34899. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34900. if (this._metallicTexture) {
  34901. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  34902. return false;
  34903. }
  34904. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  34905. defines.METALLICWORKFLOW = true;
  34906. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  34907. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  34908. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  34909. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  34910. }
  34911. else if (this._reflectivityTexture) {
  34912. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  34913. return false;
  34914. }
  34915. defines.METALLICWORKFLOW = false;
  34916. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  34917. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  34918. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  34919. }
  34920. else {
  34921. defines.METALLICWORKFLOW = false;
  34922. defines.REFLECTIVITY = false;
  34923. }
  34924. if (this._microSurfaceTexture) {
  34925. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  34926. return false;
  34927. }
  34928. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  34929. }
  34930. else {
  34931. defines.MICROSURFACEMAP = false;
  34932. }
  34933. }
  34934. else {
  34935. defines.REFLECTIVITY = false;
  34936. defines.MICROSURFACEMAP = false;
  34937. }
  34938. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34939. // Bump texure can not be none blocking.
  34940. if (!this._bumpTexture.isReady()) {
  34941. return false;
  34942. }
  34943. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34944. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34945. defines.PARALLAX = true;
  34946. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  34947. }
  34948. else {
  34949. defines.PARALLAX = false;
  34950. }
  34951. }
  34952. else {
  34953. defines.BUMP = false;
  34954. }
  34955. var refractionTexture = this._getRefractionTexture();
  34956. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34957. if (!refractionTexture.isReadyOrNotBlocking()) {
  34958. return false;
  34959. }
  34960. defines.REFRACTION = true;
  34961. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  34962. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  34963. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  34964. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34965. if (this._linkRefractionWithTransparency) {
  34966. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  34967. }
  34968. }
  34969. else {
  34970. defines.REFRACTION = false;
  34971. }
  34972. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34973. // This is blocking.
  34974. if (!this._environmentBRDFTexture.isReady()) {
  34975. return false;
  34976. }
  34977. defines.ENVIRONMENTBRDF = true;
  34978. }
  34979. else {
  34980. defines.ENVIRONMENTBRDF = false;
  34981. }
  34982. if (this._shouldUseAlphaFromAlbedoTexture()) {
  34983. defines.ALPHAFROMALBEDO = true;
  34984. }
  34985. else {
  34986. defines.ALPHAFROMALBEDO = false;
  34987. }
  34988. }
  34989. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34990. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  34991. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  34992. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  34993. defines.METALLICWORKFLOW = true;
  34994. }
  34995. else {
  34996. defines.METALLICWORKFLOW = false;
  34997. }
  34998. if (!this.backFaceCulling && this._twoSidedLighting) {
  34999. defines.TWOSIDEDLIGHTING = true;
  35000. }
  35001. else {
  35002. defines.TWOSIDEDLIGHTING = false;
  35003. }
  35004. defines.ALPHATESTVALUE = this._alphaCutOff;
  35005. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35006. defines.ALPHABLEND = this.needAlphaBlending();
  35007. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35008. }
  35009. if (defines._areImageProcessingDirty) {
  35010. if (!this._imageProcessingConfiguration.isReady()) {
  35011. return false;
  35012. }
  35013. this._imageProcessingConfiguration.prepareDefines(defines);
  35014. }
  35015. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35016. // Misc.
  35017. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35018. // Values that need to be evaluated on every frame
  35019. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35020. // Attribs
  35021. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35022. if (mesh) {
  35023. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35024. mesh.createNormals(true);
  35025. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35026. }
  35027. }
  35028. }
  35029. // Get correct effect
  35030. if (defines.isDirty) {
  35031. defines.markAsProcessed();
  35032. scene.resetCachedMaterial();
  35033. // Fallbacks
  35034. var fallbacks = new BABYLON.EffectFallbacks();
  35035. if (defines.ENVIRONMENTBRDF) {
  35036. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  35037. }
  35038. if (defines.REFLECTION) {
  35039. fallbacks.addFallback(0, "REFLECTION");
  35040. }
  35041. if (defines.REFRACTION) {
  35042. fallbacks.addFallback(0, "REFRACTION");
  35043. }
  35044. if (defines.REFLECTIVITY) {
  35045. fallbacks.addFallback(0, "REFLECTIVITY");
  35046. }
  35047. if (defines.BUMP) {
  35048. fallbacks.addFallback(0, "BUMP");
  35049. }
  35050. if (defines.PARALLAX) {
  35051. fallbacks.addFallback(1, "PARALLAX");
  35052. }
  35053. if (defines.PARALLAXOCCLUSION) {
  35054. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35055. }
  35056. if (defines.SPECULAROVERALPHA) {
  35057. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35058. }
  35059. if (defines.FOG) {
  35060. fallbacks.addFallback(1, "FOG");
  35061. }
  35062. if (defines.POINTSIZE) {
  35063. fallbacks.addFallback(0, "POINTSIZE");
  35064. }
  35065. if (defines.LOGARITHMICDEPTH) {
  35066. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35067. }
  35068. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35069. if (defines.SPECULARTERM) {
  35070. fallbacks.addFallback(0, "SPECULARTERM");
  35071. }
  35072. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35073. fallbacks.addCPUSkinningFallback(0, mesh);
  35074. }
  35075. //Attributes
  35076. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35077. if (defines.NORMAL) {
  35078. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35079. }
  35080. if (defines.TANGENT) {
  35081. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35082. }
  35083. if (defines.UV1) {
  35084. attribs.push(BABYLON.VertexBuffer.UVKind);
  35085. }
  35086. if (defines.UV2) {
  35087. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35088. }
  35089. if (defines.VERTEXCOLOR) {
  35090. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35091. }
  35092. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35093. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35094. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35095. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35096. "vFogInfos", "vFogColor", "pointSize",
  35097. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35098. "mBones",
  35099. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35100. "vLightingIntensity",
  35101. "logarithmicDepthConstant",
  35102. "vSphericalX", "vSphericalY", "vSphericalZ",
  35103. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35104. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35105. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35106. "vTangentSpaceParams"
  35107. ];
  35108. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35109. "bumpSampler", "lightmapSampler", "opacitySampler",
  35110. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35111. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35112. "microSurfaceSampler", "environmentBrdfSampler"];
  35113. var uniformBuffers = ["Material", "Scene"];
  35114. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35115. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35116. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35117. uniformsNames: uniforms,
  35118. uniformBuffersNames: uniformBuffers,
  35119. samplers: samplers,
  35120. defines: defines,
  35121. maxSimultaneousLights: this._maxSimultaneousLights
  35122. });
  35123. var onCompiled = function (effect) {
  35124. if (_this.onCompiled) {
  35125. _this.onCompiled(effect);
  35126. }
  35127. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35128. };
  35129. var join = defines.toString();
  35130. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35131. attributes: attribs,
  35132. uniformsNames: uniforms,
  35133. uniformBuffersNames: uniformBuffers,
  35134. samplers: samplers,
  35135. defines: join,
  35136. fallbacks: fallbacks,
  35137. onCompiled: onCompiled,
  35138. onError: this.onError,
  35139. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35140. }, engine), defines);
  35141. this.buildUniformLayout();
  35142. }
  35143. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35144. return false;
  35145. }
  35146. defines._renderId = scene.getRenderId();
  35147. this._wasPreviouslyReady = true;
  35148. return true;
  35149. };
  35150. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35151. // Order is important !
  35152. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35153. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35154. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35155. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35156. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35157. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35158. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35159. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35160. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35161. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35162. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35163. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35164. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35165. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35166. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35167. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35168. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35169. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35170. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35171. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35172. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35173. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35174. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35175. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35176. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35177. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35178. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35179. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35180. this._uniformBuffer.addUniform("pointSize", 1);
  35181. this._uniformBuffer.create();
  35182. };
  35183. PBRBaseMaterial.prototype.unbind = function () {
  35184. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35185. this._uniformBuffer.setTexture("reflectionSampler", null);
  35186. }
  35187. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35188. this._uniformBuffer.setTexture("refractionSampler", null);
  35189. }
  35190. _super.prototype.unbind.call(this);
  35191. };
  35192. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35193. this._activeEffect.setMatrix("world", world);
  35194. };
  35195. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35196. var scene = this.getScene();
  35197. var defines = subMesh._materialDefines;
  35198. if (!defines) {
  35199. return;
  35200. }
  35201. var effect = subMesh.effect;
  35202. if (!effect) {
  35203. return;
  35204. }
  35205. this._activeEffect = effect;
  35206. // Matrices
  35207. this.bindOnlyWorldMatrix(world);
  35208. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35209. // Bones
  35210. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35211. var reflectionTexture = null;
  35212. if (mustRebind) {
  35213. this._uniformBuffer.bindToEffect(effect, "Material");
  35214. this.bindViewProjection(effect);
  35215. reflectionTexture = this._getReflectionTexture();
  35216. var refractionTexture = this._getRefractionTexture();
  35217. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35218. // Texture uniforms
  35219. if (scene.texturesEnabled) {
  35220. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35221. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35222. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35223. }
  35224. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35225. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35226. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35227. }
  35228. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35229. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35230. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35231. }
  35232. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35233. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35234. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35235. var polynomials = reflectionTexture.sphericalPolynomial;
  35236. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35237. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35238. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35239. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35240. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35241. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35242. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35243. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35244. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35245. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35246. }
  35247. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35248. }
  35249. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35250. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35251. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35252. }
  35253. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35254. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35255. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35256. }
  35257. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35258. if (this._metallicTexture) {
  35259. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35260. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35261. }
  35262. else if (this._reflectivityTexture) {
  35263. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35264. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35265. }
  35266. if (this._microSurfaceTexture) {
  35267. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35268. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35269. }
  35270. }
  35271. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35272. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35273. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35274. if (scene._mirroredCameraPosition) {
  35275. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35276. }
  35277. else {
  35278. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35279. }
  35280. }
  35281. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35282. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35283. var depth = 1.0;
  35284. if (!refractionTexture.isCube) {
  35285. if (refractionTexture.depth) {
  35286. depth = refractionTexture.depth;
  35287. }
  35288. }
  35289. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35290. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35291. }
  35292. }
  35293. // Point size
  35294. if (this.pointsCloud) {
  35295. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35296. }
  35297. // Colors
  35298. if (defines.METALLICWORKFLOW) {
  35299. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35300. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35301. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35302. }
  35303. else {
  35304. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35305. }
  35306. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35307. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35308. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35309. // Misc
  35310. this._lightingInfos.x = this._directIntensity;
  35311. this._lightingInfos.y = this._emissiveIntensity;
  35312. this._lightingInfos.z = this._environmentIntensity;
  35313. this._lightingInfos.w = this._specularIntensity;
  35314. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35315. }
  35316. // Textures
  35317. if (scene.texturesEnabled) {
  35318. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35319. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35320. }
  35321. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35322. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35323. }
  35324. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35325. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35326. }
  35327. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35328. if (defines.LODBASEDMICROSFURACE) {
  35329. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35330. }
  35331. else {
  35332. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35333. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35334. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35335. }
  35336. }
  35337. if (defines.ENVIRONMENTBRDF) {
  35338. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35339. }
  35340. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35341. if (defines.LODBASEDMICROSFURACE) {
  35342. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35343. }
  35344. else {
  35345. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35346. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35347. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35348. }
  35349. }
  35350. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35351. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35352. }
  35353. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35354. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35355. }
  35356. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35357. if (this._metallicTexture) {
  35358. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35359. }
  35360. else if (this._reflectivityTexture) {
  35361. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35362. }
  35363. if (this._microSurfaceTexture) {
  35364. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35365. }
  35366. }
  35367. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35368. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35369. }
  35370. }
  35371. // Clip plane
  35372. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35373. // Colors
  35374. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35375. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  35376. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35377. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35378. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35379. }
  35380. if (mustRebind || !this.isFrozen) {
  35381. // Lights
  35382. if (scene.lightsEnabled && !this._disableLighting) {
  35383. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35384. }
  35385. // View
  35386. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35387. this.bindView(effect);
  35388. }
  35389. // Fog
  35390. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35391. // Morph targets
  35392. if (defines.NUM_MORPH_INFLUENCERS) {
  35393. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35394. }
  35395. // image processing
  35396. this._imageProcessingConfiguration.bind(this._activeEffect);
  35397. // Log. depth
  35398. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35399. }
  35400. this._uniformBuffer.update();
  35401. this._afterBind(mesh);
  35402. };
  35403. PBRBaseMaterial.prototype.getAnimatables = function () {
  35404. var results = [];
  35405. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35406. results.push(this._albedoTexture);
  35407. }
  35408. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35409. results.push(this._ambientTexture);
  35410. }
  35411. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35412. results.push(this._opacityTexture);
  35413. }
  35414. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35415. results.push(this._reflectionTexture);
  35416. }
  35417. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35418. results.push(this._emissiveTexture);
  35419. }
  35420. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35421. results.push(this._metallicTexture);
  35422. }
  35423. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35424. results.push(this._reflectivityTexture);
  35425. }
  35426. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35427. results.push(this._bumpTexture);
  35428. }
  35429. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35430. results.push(this._lightmapTexture);
  35431. }
  35432. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35433. results.push(this._refractionTexture);
  35434. }
  35435. return results;
  35436. };
  35437. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35438. if (this._reflectionTexture) {
  35439. return this._reflectionTexture;
  35440. }
  35441. return this.getScene().environmentTexture;
  35442. };
  35443. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35444. if (this._refractionTexture) {
  35445. return this._refractionTexture;
  35446. }
  35447. if (this._linkRefractionWithTransparency) {
  35448. return this.getScene().environmentTexture;
  35449. }
  35450. return null;
  35451. };
  35452. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35453. if (forceDisposeTextures) {
  35454. if (this._albedoTexture) {
  35455. this._albedoTexture.dispose();
  35456. }
  35457. if (this._ambientTexture) {
  35458. this._ambientTexture.dispose();
  35459. }
  35460. if (this._opacityTexture) {
  35461. this._opacityTexture.dispose();
  35462. }
  35463. if (this._reflectionTexture) {
  35464. this._reflectionTexture.dispose();
  35465. }
  35466. if (this._environmentBRDFTexture) {
  35467. this._environmentBRDFTexture.dispose();
  35468. }
  35469. if (this._emissiveTexture) {
  35470. this._emissiveTexture.dispose();
  35471. }
  35472. if (this._metallicTexture) {
  35473. this._metallicTexture.dispose();
  35474. }
  35475. if (this._reflectivityTexture) {
  35476. this._reflectivityTexture.dispose();
  35477. }
  35478. if (this._bumpTexture) {
  35479. this._bumpTexture.dispose();
  35480. }
  35481. if (this._lightmapTexture) {
  35482. this._lightmapTexture.dispose();
  35483. }
  35484. if (this._refractionTexture) {
  35485. this._refractionTexture.dispose();
  35486. }
  35487. }
  35488. this._renderTargets.dispose();
  35489. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35490. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35491. }
  35492. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35493. };
  35494. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35495. __decorate([
  35496. BABYLON.serializeAsImageProcessingConfiguration()
  35497. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35498. __decorate([
  35499. BABYLON.serialize()
  35500. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35501. return PBRBaseMaterial;
  35502. }(BABYLON.PushMaterial));
  35503. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35504. })(BABYLON || (BABYLON = {}));
  35505. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35506. var BABYLON;
  35507. (function (BABYLON) {
  35508. var Internals;
  35509. (function (Internals) {
  35510. /**
  35511. * The Physically based simple base material of BJS.
  35512. *
  35513. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35514. * It is used as the base class for both the specGloss and metalRough conventions.
  35515. */
  35516. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35517. __extends(PBRBaseSimpleMaterial, _super);
  35518. /**
  35519. * Instantiates a new PBRMaterial instance.
  35520. *
  35521. * @param name The material name
  35522. * @param scene The scene the material will be use in.
  35523. */
  35524. function PBRBaseSimpleMaterial(name, scene) {
  35525. var _this = _super.call(this, name, scene) || this;
  35526. /**
  35527. * Number of Simultaneous lights allowed on the material.
  35528. */
  35529. _this.maxSimultaneousLights = 4;
  35530. /**
  35531. * If sets to true, disables all the lights affecting the material.
  35532. */
  35533. _this.disableLighting = false;
  35534. /**
  35535. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35536. */
  35537. _this.invertNormalMapX = false;
  35538. /**
  35539. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35540. */
  35541. _this.invertNormalMapY = false;
  35542. /**
  35543. * Emissivie color used to self-illuminate the model.
  35544. */
  35545. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35546. /**
  35547. * Occlusion Channel Strenght.
  35548. */
  35549. _this.occlusionStrength = 1.0;
  35550. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35551. _this._useAmbientInGrayScale = true;
  35552. return _this;
  35553. }
  35554. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35555. /**
  35556. * Gets the current transparency mode.
  35557. */
  35558. get: function () {
  35559. return this._transparencyMode;
  35560. },
  35561. /**
  35562. * Sets the transparency mode of the material.
  35563. */
  35564. set: function (value) {
  35565. if (this._transparencyMode === value) {
  35566. return;
  35567. }
  35568. this._transparencyMode = value;
  35569. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35570. this._forceAlphaTest = true;
  35571. }
  35572. else {
  35573. this._forceAlphaTest = false;
  35574. }
  35575. this._markAllSubMeshesAsTexturesDirty();
  35576. },
  35577. enumerable: true,
  35578. configurable: true
  35579. });
  35580. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35581. /**
  35582. * Gets the current double sided mode.
  35583. */
  35584. get: function () {
  35585. return this._twoSidedLighting;
  35586. },
  35587. /**
  35588. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35589. */
  35590. set: function (value) {
  35591. if (this._twoSidedLighting === value) {
  35592. return;
  35593. }
  35594. this._twoSidedLighting = value;
  35595. this.backFaceCulling = !value;
  35596. this._markAllSubMeshesAsTexturesDirty();
  35597. },
  35598. enumerable: true,
  35599. configurable: true
  35600. });
  35601. /**
  35602. * Specifies wether or not the alpha value of the albedo texture should be used.
  35603. */
  35604. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35605. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35606. };
  35607. /**
  35608. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35609. */
  35610. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35611. if (this._linkRefractionWithTransparency) {
  35612. return false;
  35613. }
  35614. return (this.alpha < 1.0) ||
  35615. (this._shouldUseAlphaFromAlbedoTexture() &&
  35616. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35617. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35618. };
  35619. /**
  35620. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35621. */
  35622. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35623. if (this._linkRefractionWithTransparency) {
  35624. return false;
  35625. }
  35626. return this._shouldUseAlphaFromAlbedoTexture() &&
  35627. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35628. };
  35629. /**
  35630. * Return the active textures of the material.
  35631. */
  35632. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  35633. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35634. if (this.environmentTexture) {
  35635. activeTextures.push(this.environmentTexture);
  35636. }
  35637. if (this.normalTexture) {
  35638. activeTextures.push(this.normalTexture);
  35639. }
  35640. if (this.emissiveTexture) {
  35641. activeTextures.push(this.emissiveTexture);
  35642. }
  35643. if (this.occlusionTexture) {
  35644. activeTextures.push(this.occlusionTexture);
  35645. }
  35646. return activeTextures;
  35647. };
  35648. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  35649. return "PBRBaseSimpleMaterial";
  35650. };
  35651. __decorate([
  35652. BABYLON.serialize(),
  35653. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35654. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35655. __decorate([
  35656. BABYLON.serialize(),
  35657. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35658. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35659. __decorate([
  35660. BABYLON.serializeAsTexture(),
  35661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35662. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35663. __decorate([
  35664. BABYLON.serialize(),
  35665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35666. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35667. __decorate([
  35668. BABYLON.serialize(),
  35669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35670. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35671. __decorate([
  35672. BABYLON.serializeAsTexture(),
  35673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35674. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35675. __decorate([
  35676. BABYLON.serializeAsColor3("emissive"),
  35677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35678. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35679. __decorate([
  35680. BABYLON.serializeAsTexture(),
  35681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35682. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35683. __decorate([
  35684. BABYLON.serialize(),
  35685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35686. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35687. __decorate([
  35688. BABYLON.serializeAsTexture(),
  35689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35690. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35691. __decorate([
  35692. BABYLON.serialize(),
  35693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35694. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35695. __decorate([
  35696. BABYLON.serialize()
  35697. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35698. __decorate([
  35699. BABYLON.serialize()
  35700. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35701. return PBRBaseSimpleMaterial;
  35702. }(BABYLON.PBRBaseMaterial));
  35703. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35704. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35705. })(BABYLON || (BABYLON = {}));
  35706. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35707. var BABYLON;
  35708. (function (BABYLON) {
  35709. /**
  35710. * The Physically based material of BJS.
  35711. *
  35712. * This offers the main features of a standard PBR material.
  35713. * For more information, please refer to the documentation :
  35714. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35715. */
  35716. var PBRMaterial = /** @class */ (function (_super) {
  35717. __extends(PBRMaterial, _super);
  35718. /**
  35719. * Instantiates a new PBRMaterial instance.
  35720. *
  35721. * @param name The material name
  35722. * @param scene The scene the material will be use in.
  35723. */
  35724. function PBRMaterial(name, scene) {
  35725. var _this = _super.call(this, name, scene) || this;
  35726. /**
  35727. * Intensity of the direct lights e.g. the four lights available in your scene.
  35728. * This impacts both the direct diffuse and specular highlights.
  35729. */
  35730. _this.directIntensity = 1.0;
  35731. /**
  35732. * Intensity of the emissive part of the material.
  35733. * This helps controlling the emissive effect without modifying the emissive color.
  35734. */
  35735. _this.emissiveIntensity = 1.0;
  35736. /**
  35737. * Intensity of the environment e.g. how much the environment will light the object
  35738. * either through harmonics for rough material or through the refelction for shiny ones.
  35739. */
  35740. _this.environmentIntensity = 1.0;
  35741. /**
  35742. * This is a special control allowing the reduction of the specular highlights coming from the
  35743. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35744. */
  35745. _this.specularIntensity = 1.0;
  35746. /**
  35747. * Debug Control allowing disabling the bump map on this material.
  35748. */
  35749. _this.disableBumpMap = false;
  35750. /**
  35751. * AKA Occlusion Texture Intensity in other nomenclature.
  35752. */
  35753. _this.ambientTextureStrength = 1.0;
  35754. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35755. /**
  35756. * AKA Diffuse Color in other nomenclature.
  35757. */
  35758. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35759. /**
  35760. * AKA Specular Color in other nomenclature.
  35761. */
  35762. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35763. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  35764. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35765. /**
  35766. * AKA Glossiness in other nomenclature.
  35767. */
  35768. _this.microSurface = 1.0;
  35769. /**
  35770. * source material index of refraction (IOR)' / 'destination material IOR.
  35771. */
  35772. _this.indexOfRefraction = 0.66;
  35773. /**
  35774. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35775. */
  35776. _this.invertRefractionY = false;
  35777. /**
  35778. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35779. * Materials half opaque for instance using refraction could benefit from this control.
  35780. */
  35781. _this.linkRefractionWithTransparency = false;
  35782. _this.useLightmapAsShadowmap = false;
  35783. /**
  35784. * Specifies that the alpha is coming form the albedo channel alpha channel.
  35785. */
  35786. _this.useAlphaFromAlbedoTexture = false;
  35787. /**
  35788. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35789. */
  35790. _this.forceAlphaTest = false;
  35791. /**
  35792. * Defines the alpha limits in alpha test mode.
  35793. */
  35794. _this.alphaCutOff = 0.4;
  35795. /**
  35796. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35797. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35798. */
  35799. _this.useSpecularOverAlpha = true;
  35800. /**
  35801. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35802. */
  35803. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35804. /**
  35805. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35806. */
  35807. _this.useRoughnessFromMetallicTextureAlpha = true;
  35808. /**
  35809. * Specifies if the metallic texture contains the roughness information in its green channel.
  35810. */
  35811. _this.useRoughnessFromMetallicTextureGreen = false;
  35812. /**
  35813. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35814. */
  35815. _this.useMetallnessFromMetallicTextureBlue = false;
  35816. /**
  35817. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35818. */
  35819. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35820. /**
  35821. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35822. */
  35823. _this.useAmbientInGrayScale = false;
  35824. /**
  35825. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35826. * The material will try to infer what glossiness each pixel should be.
  35827. */
  35828. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  35829. /**
  35830. * BJS is using an harcoded light falloff based on a manually sets up range.
  35831. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35832. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35833. */
  35834. _this.usePhysicalLightFalloff = true;
  35835. /**
  35836. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35837. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35838. */
  35839. _this.useRadianceOverAlpha = true;
  35840. /**
  35841. * Allows using the bump map in parallax mode.
  35842. */
  35843. _this.useParallax = false;
  35844. /**
  35845. * Allows using the bump map in parallax occlusion mode.
  35846. */
  35847. _this.useParallaxOcclusion = false;
  35848. /**
  35849. * Controls the scale bias of the parallax mode.
  35850. */
  35851. _this.parallaxScaleBias = 0.05;
  35852. /**
  35853. * If sets to true, disables all the lights affecting the material.
  35854. */
  35855. _this.disableLighting = false;
  35856. /**
  35857. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35858. */
  35859. _this.forceIrradianceInFragment = false;
  35860. /**
  35861. * Number of Simultaneous lights allowed on the material.
  35862. */
  35863. _this.maxSimultaneousLights = 4;
  35864. /**
  35865. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35866. */
  35867. _this.invertNormalMapX = false;
  35868. /**
  35869. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35870. */
  35871. _this.invertNormalMapY = false;
  35872. /**
  35873. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35874. */
  35875. _this.twoSidedLighting = false;
  35876. /**
  35877. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35878. * And/Or occlude the blended part.
  35879. */
  35880. _this.useAlphaFresnel = false;
  35881. /**
  35882. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35883. * And/Or occlude the blended part.
  35884. */
  35885. _this.environmentBRDFTexture = null;
  35886. /**
  35887. * Force normal to face away from face.
  35888. * (Temporary internal fix to remove before 3.1)
  35889. */
  35890. _this.forceNormalForward = false;
  35891. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35892. return _this;
  35893. }
  35894. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  35895. /**
  35896. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  35897. */
  35898. get: function () {
  35899. return this._PBRMATERIAL_OPAQUE;
  35900. },
  35901. enumerable: true,
  35902. configurable: true
  35903. });
  35904. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  35905. /**
  35906. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  35907. */
  35908. get: function () {
  35909. return this._PBRMATERIAL_ALPHATEST;
  35910. },
  35911. enumerable: true,
  35912. configurable: true
  35913. });
  35914. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  35915. /**
  35916. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35917. */
  35918. get: function () {
  35919. return this._PBRMATERIAL_ALPHABLEND;
  35920. },
  35921. enumerable: true,
  35922. configurable: true
  35923. });
  35924. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  35925. /**
  35926. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35927. * They are also discarded below the alpha cutoff threshold to improve performances.
  35928. */
  35929. get: function () {
  35930. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  35931. },
  35932. enumerable: true,
  35933. configurable: true
  35934. });
  35935. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  35936. /**
  35937. * Gets the image processing configuration used either in this material.
  35938. */
  35939. get: function () {
  35940. return this._imageProcessingConfiguration;
  35941. },
  35942. /**
  35943. * Sets the Default image processing configuration used either in the this material.
  35944. *
  35945. * If sets to null, the scene one is in use.
  35946. */
  35947. set: function (value) {
  35948. this._attachImageProcessingConfiguration(value);
  35949. // Ensure the effect will be rebuilt.
  35950. this._markAllSubMeshesAsTexturesDirty();
  35951. },
  35952. enumerable: true,
  35953. configurable: true
  35954. });
  35955. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  35956. /**
  35957. * Gets wether the color curves effect is enabled.
  35958. */
  35959. get: function () {
  35960. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35961. },
  35962. /**
  35963. * Sets wether the color curves effect is enabled.
  35964. */
  35965. set: function (value) {
  35966. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35967. },
  35968. enumerable: true,
  35969. configurable: true
  35970. });
  35971. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  35972. /**
  35973. * Gets wether the color grading effect is enabled.
  35974. */
  35975. get: function () {
  35976. return this.imageProcessingConfiguration.colorGradingEnabled;
  35977. },
  35978. /**
  35979. * Gets wether the color grading effect is enabled.
  35980. */
  35981. set: function (value) {
  35982. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35983. },
  35984. enumerable: true,
  35985. configurable: true
  35986. });
  35987. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  35988. /**
  35989. * Gets wether tonemapping is enabled or not.
  35990. */
  35991. get: function () {
  35992. return this._imageProcessingConfiguration.toneMappingEnabled;
  35993. },
  35994. /**
  35995. * Sets wether tonemapping is enabled or not
  35996. */
  35997. set: function (value) {
  35998. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35999. },
  36000. enumerable: true,
  36001. configurable: true
  36002. });
  36003. ;
  36004. ;
  36005. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36006. /**
  36007. * The camera exposure used on this material.
  36008. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36009. * This corresponds to a photographic exposure.
  36010. */
  36011. get: function () {
  36012. return this._imageProcessingConfiguration.exposure;
  36013. },
  36014. /**
  36015. * The camera exposure used on this material.
  36016. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36017. * This corresponds to a photographic exposure.
  36018. */
  36019. set: function (value) {
  36020. this._imageProcessingConfiguration.exposure = value;
  36021. },
  36022. enumerable: true,
  36023. configurable: true
  36024. });
  36025. ;
  36026. ;
  36027. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36028. /**
  36029. * Gets The camera contrast used on this material.
  36030. */
  36031. get: function () {
  36032. return this._imageProcessingConfiguration.contrast;
  36033. },
  36034. /**
  36035. * Sets The camera contrast used on this material.
  36036. */
  36037. set: function (value) {
  36038. this._imageProcessingConfiguration.contrast = value;
  36039. },
  36040. enumerable: true,
  36041. configurable: true
  36042. });
  36043. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36044. /**
  36045. * Gets the Color Grading 2D Lookup Texture.
  36046. */
  36047. get: function () {
  36048. return this._imageProcessingConfiguration.colorGradingTexture;
  36049. },
  36050. /**
  36051. * Sets the Color Grading 2D Lookup Texture.
  36052. */
  36053. set: function (value) {
  36054. this._imageProcessingConfiguration.colorGradingTexture = value;
  36055. },
  36056. enumerable: true,
  36057. configurable: true
  36058. });
  36059. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36060. /**
  36061. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36062. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36063. * 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;
  36064. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36065. */
  36066. get: function () {
  36067. return this._imageProcessingConfiguration.colorCurves;
  36068. },
  36069. /**
  36070. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36071. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36072. * 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;
  36073. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36074. */
  36075. set: function (value) {
  36076. this._imageProcessingConfiguration.colorCurves = value;
  36077. },
  36078. enumerable: true,
  36079. configurable: true
  36080. });
  36081. PBRMaterial.prototype.getClassName = function () {
  36082. return "PBRMaterial";
  36083. };
  36084. PBRMaterial.prototype.getActiveTextures = function () {
  36085. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36086. if (this._albedoTexture) {
  36087. activeTextures.push(this._albedoTexture);
  36088. }
  36089. if (this._ambientTexture) {
  36090. activeTextures.push(this._ambientTexture);
  36091. }
  36092. if (this._opacityTexture) {
  36093. activeTextures.push(this._opacityTexture);
  36094. }
  36095. if (this._reflectionTexture) {
  36096. activeTextures.push(this._reflectionTexture);
  36097. }
  36098. if (this._emissiveTexture) {
  36099. activeTextures.push(this._emissiveTexture);
  36100. }
  36101. if (this._reflectivityTexture) {
  36102. activeTextures.push(this._reflectivityTexture);
  36103. }
  36104. if (this._metallicTexture) {
  36105. activeTextures.push(this._metallicTexture);
  36106. }
  36107. if (this._microSurfaceTexture) {
  36108. activeTextures.push(this._microSurfaceTexture);
  36109. }
  36110. if (this._bumpTexture) {
  36111. activeTextures.push(this._bumpTexture);
  36112. }
  36113. if (this._lightmapTexture) {
  36114. activeTextures.push(this._lightmapTexture);
  36115. }
  36116. if (this._refractionTexture) {
  36117. activeTextures.push(this._refractionTexture);
  36118. }
  36119. return activeTextures;
  36120. };
  36121. PBRMaterial.prototype.hasTexture = function (texture) {
  36122. if (_super.prototype.hasTexture.call(this, texture)) {
  36123. return true;
  36124. }
  36125. if (this._albedoTexture === texture) {
  36126. return true;
  36127. }
  36128. if (this._ambientTexture === texture) {
  36129. return true;
  36130. }
  36131. if (this._opacityTexture === texture) {
  36132. return true;
  36133. }
  36134. if (this._reflectionTexture === texture) {
  36135. return true;
  36136. }
  36137. if (this._reflectivityTexture === texture) {
  36138. return true;
  36139. }
  36140. if (this._metallicTexture === texture) {
  36141. return true;
  36142. }
  36143. if (this._microSurfaceTexture === texture) {
  36144. return true;
  36145. }
  36146. if (this._bumpTexture === texture) {
  36147. return true;
  36148. }
  36149. if (this._lightmapTexture === texture) {
  36150. return true;
  36151. }
  36152. if (this._refractionTexture === texture) {
  36153. return true;
  36154. }
  36155. return false;
  36156. };
  36157. PBRMaterial.prototype.clone = function (name) {
  36158. var _this = this;
  36159. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36160. clone.id = name;
  36161. clone.name = name;
  36162. return clone;
  36163. };
  36164. PBRMaterial.prototype.serialize = function () {
  36165. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36166. serializationObject.customType = "BABYLON.PBRMaterial";
  36167. return serializationObject;
  36168. };
  36169. // Statics
  36170. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36171. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36172. };
  36173. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36174. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36175. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36176. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36177. __decorate([
  36178. BABYLON.serialize(),
  36179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36180. ], PBRMaterial.prototype, "directIntensity", void 0);
  36181. __decorate([
  36182. BABYLON.serialize(),
  36183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36184. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36185. __decorate([
  36186. BABYLON.serialize(),
  36187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36188. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36189. __decorate([
  36190. BABYLON.serialize(),
  36191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36192. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36193. __decorate([
  36194. BABYLON.serialize(),
  36195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36196. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36197. __decorate([
  36198. BABYLON.serializeAsTexture(),
  36199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36200. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36201. __decorate([
  36202. BABYLON.serializeAsTexture(),
  36203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36204. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36205. __decorate([
  36206. BABYLON.serialize(),
  36207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36208. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36209. __decorate([
  36210. BABYLON.serializeAsTexture(),
  36211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36212. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36213. __decorate([
  36214. BABYLON.serializeAsTexture(),
  36215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36216. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36217. __decorate([
  36218. BABYLON.serializeAsTexture(),
  36219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36220. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36221. __decorate([
  36222. BABYLON.serializeAsTexture(),
  36223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36224. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36225. __decorate([
  36226. BABYLON.serializeAsTexture(),
  36227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36228. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36229. __decorate([
  36230. BABYLON.serialize(),
  36231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36232. ], PBRMaterial.prototype, "metallic", void 0);
  36233. __decorate([
  36234. BABYLON.serialize(),
  36235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36236. ], PBRMaterial.prototype, "roughness", void 0);
  36237. __decorate([
  36238. BABYLON.serializeAsTexture(),
  36239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36240. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36241. __decorate([
  36242. BABYLON.serializeAsTexture(),
  36243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36244. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36245. __decorate([
  36246. BABYLON.serializeAsTexture(),
  36247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36248. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36249. __decorate([
  36250. BABYLON.serializeAsTexture(),
  36251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36252. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36253. __decorate([
  36254. BABYLON.serializeAsColor3("ambient"),
  36255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36256. ], PBRMaterial.prototype, "ambientColor", void 0);
  36257. __decorate([
  36258. BABYLON.serializeAsColor3("albedo"),
  36259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36260. ], PBRMaterial.prototype, "albedoColor", void 0);
  36261. __decorate([
  36262. BABYLON.serializeAsColor3("reflectivity"),
  36263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36264. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36265. __decorate([
  36266. BABYLON.serializeAsColor3("reflection"),
  36267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36268. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36269. __decorate([
  36270. BABYLON.serializeAsColor3("emissive"),
  36271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36272. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36273. __decorate([
  36274. BABYLON.serialize(),
  36275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36276. ], PBRMaterial.prototype, "microSurface", void 0);
  36277. __decorate([
  36278. BABYLON.serialize(),
  36279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36280. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36281. __decorate([
  36282. BABYLON.serialize(),
  36283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36284. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36285. __decorate([
  36286. BABYLON.serialize(),
  36287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36288. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36289. __decorate([
  36290. BABYLON.serialize(),
  36291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36292. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36293. __decorate([
  36294. BABYLON.serialize(),
  36295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36296. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36297. __decorate([
  36298. BABYLON.serialize(),
  36299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36300. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36301. __decorate([
  36302. BABYLON.serialize(),
  36303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36304. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36305. __decorate([
  36306. BABYLON.serialize(),
  36307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36308. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36309. __decorate([
  36310. BABYLON.serialize(),
  36311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36312. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36313. __decorate([
  36314. BABYLON.serialize(),
  36315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36316. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36317. __decorate([
  36318. BABYLON.serialize(),
  36319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36320. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36321. __decorate([
  36322. BABYLON.serialize(),
  36323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36324. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36325. __decorate([
  36326. BABYLON.serialize(),
  36327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36328. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36329. __decorate([
  36330. BABYLON.serialize(),
  36331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36332. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36333. __decorate([
  36334. BABYLON.serialize(),
  36335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36336. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36337. __decorate([
  36338. BABYLON.serialize(),
  36339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36340. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36341. __decorate([
  36342. BABYLON.serialize(),
  36343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36344. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36345. __decorate([
  36346. BABYLON.serialize(),
  36347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36348. ], PBRMaterial.prototype, "useParallax", void 0);
  36349. __decorate([
  36350. BABYLON.serialize(),
  36351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36352. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36353. __decorate([
  36354. BABYLON.serialize(),
  36355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36356. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36357. __decorate([
  36358. BABYLON.serialize(),
  36359. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36360. ], PBRMaterial.prototype, "disableLighting", void 0);
  36361. __decorate([
  36362. BABYLON.serialize(),
  36363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36364. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36365. __decorate([
  36366. BABYLON.serialize(),
  36367. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36368. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36369. __decorate([
  36370. BABYLON.serialize(),
  36371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36372. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36373. __decorate([
  36374. BABYLON.serialize(),
  36375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36376. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36377. __decorate([
  36378. BABYLON.serialize(),
  36379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36380. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36381. __decorate([
  36382. BABYLON.serialize(),
  36383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36384. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36385. __decorate([
  36386. BABYLON.serializeAsTexture(),
  36387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36388. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36389. __decorate([
  36390. BABYLON.serialize(),
  36391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36392. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36393. return PBRMaterial;
  36394. }(BABYLON.PBRBaseMaterial));
  36395. BABYLON.PBRMaterial = PBRMaterial;
  36396. })(BABYLON || (BABYLON = {}));
  36397. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36398. var BABYLON;
  36399. (function (BABYLON) {
  36400. /**
  36401. * The PBR material of BJS following the metal roughness convention.
  36402. *
  36403. * This fits to the PBR convention in the GLTF definition:
  36404. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36405. */
  36406. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36407. __extends(PBRMetallicRoughnessMaterial, _super);
  36408. /**
  36409. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36410. *
  36411. * @param name The material name
  36412. * @param scene The scene the material will be use in.
  36413. */
  36414. function PBRMetallicRoughnessMaterial(name, scene) {
  36415. var _this = _super.call(this, name, scene) || this;
  36416. _this._useRoughnessFromMetallicTextureAlpha = false;
  36417. _this._useRoughnessFromMetallicTextureGreen = true;
  36418. _this._useMetallnessFromMetallicTextureBlue = true;
  36419. return _this;
  36420. }
  36421. /**
  36422. * Return the currrent class name of the material.
  36423. */
  36424. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36425. return "PBRMetallicRoughnessMaterial";
  36426. };
  36427. /**
  36428. * Return the active textures of the material.
  36429. */
  36430. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36431. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36432. if (this.baseTexture) {
  36433. activeTextures.push(this.baseTexture);
  36434. }
  36435. if (this.metallicRoughnessTexture) {
  36436. activeTextures.push(this.metallicRoughnessTexture);
  36437. }
  36438. return activeTextures;
  36439. };
  36440. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36441. if (_super.prototype.hasTexture.call(this, texture)) {
  36442. return true;
  36443. }
  36444. if (this.baseTexture === texture) {
  36445. return true;
  36446. }
  36447. if (this.metallicRoughnessTexture === texture) {
  36448. return true;
  36449. }
  36450. return false;
  36451. };
  36452. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36453. var _this = this;
  36454. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36455. clone.id = name;
  36456. clone.name = name;
  36457. return clone;
  36458. };
  36459. /**
  36460. * Serialize the material to a parsable JSON object.
  36461. */
  36462. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36463. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36464. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36465. return serializationObject;
  36466. };
  36467. /**
  36468. * Parses a JSON object correponding to the serialize function.
  36469. */
  36470. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36471. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36472. };
  36473. __decorate([
  36474. BABYLON.serializeAsColor3(),
  36475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36476. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36477. __decorate([
  36478. BABYLON.serializeAsTexture(),
  36479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36480. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36481. __decorate([
  36482. BABYLON.serialize(),
  36483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36484. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36485. __decorate([
  36486. BABYLON.serialize(),
  36487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36488. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36489. __decorate([
  36490. BABYLON.serializeAsTexture(),
  36491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36492. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36493. return PBRMetallicRoughnessMaterial;
  36494. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36495. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36496. })(BABYLON || (BABYLON = {}));
  36497. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36498. var BABYLON;
  36499. (function (BABYLON) {
  36500. /**
  36501. * The PBR material of BJS following the specular glossiness convention.
  36502. *
  36503. * This fits to the PBR convention in the GLTF definition:
  36504. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36505. */
  36506. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36507. __extends(PBRSpecularGlossinessMaterial, _super);
  36508. /**
  36509. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36510. *
  36511. * @param name The material name
  36512. * @param scene The scene the material will be use in.
  36513. */
  36514. function PBRSpecularGlossinessMaterial(name, scene) {
  36515. var _this = _super.call(this, name, scene) || this;
  36516. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36517. return _this;
  36518. }
  36519. /**
  36520. * Return the currrent class name of the material.
  36521. */
  36522. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36523. return "PBRSpecularGlossinessMaterial";
  36524. };
  36525. /**
  36526. * Return the active textures of the material.
  36527. */
  36528. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36529. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36530. if (this.diffuseTexture) {
  36531. activeTextures.push(this.diffuseTexture);
  36532. }
  36533. if (this.specularGlossinessTexture) {
  36534. activeTextures.push(this.specularGlossinessTexture);
  36535. }
  36536. return activeTextures;
  36537. };
  36538. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36539. if (_super.prototype.hasTexture.call(this, texture)) {
  36540. return true;
  36541. }
  36542. if (this.diffuseTexture === texture) {
  36543. return true;
  36544. }
  36545. if (this.specularGlossinessTexture === texture) {
  36546. return true;
  36547. }
  36548. return false;
  36549. };
  36550. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36551. var _this = this;
  36552. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36553. clone.id = name;
  36554. clone.name = name;
  36555. return clone;
  36556. };
  36557. /**
  36558. * Serialize the material to a parsable JSON object.
  36559. */
  36560. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36561. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36562. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36563. return serializationObject;
  36564. };
  36565. /**
  36566. * Parses a JSON object correponding to the serialize function.
  36567. */
  36568. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36569. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36570. };
  36571. __decorate([
  36572. BABYLON.serializeAsColor3("diffuse"),
  36573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36574. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36575. __decorate([
  36576. BABYLON.serializeAsTexture(),
  36577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36578. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36579. __decorate([
  36580. BABYLON.serializeAsColor3("specular"),
  36581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36582. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36583. __decorate([
  36584. BABYLON.serialize(),
  36585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36586. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36587. __decorate([
  36588. BABYLON.serializeAsTexture(),
  36589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36590. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36591. return PBRSpecularGlossinessMaterial;
  36592. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36593. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36594. })(BABYLON || (BABYLON = {}));
  36595. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36596. var BABYLON;
  36597. (function (BABYLON) {
  36598. BABYLON.CameraInputTypes = {};
  36599. var CameraInputsManager = /** @class */ (function () {
  36600. function CameraInputsManager(camera) {
  36601. this.attached = {};
  36602. this.camera = camera;
  36603. this.checkInputs = function () { };
  36604. }
  36605. CameraInputsManager.prototype.add = function (input) {
  36606. var type = input.getSimpleName();
  36607. if (this.attached[type]) {
  36608. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36609. return;
  36610. }
  36611. this.attached[type] = input;
  36612. input.camera = this.camera;
  36613. //for checkInputs, we are dynamically creating a function
  36614. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36615. if (input.checkInputs) {
  36616. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36617. }
  36618. if (this.attachedElement) {
  36619. input.attachControl(this.attachedElement);
  36620. }
  36621. };
  36622. CameraInputsManager.prototype.remove = function (inputToRemove) {
  36623. for (var cam in this.attached) {
  36624. var input = this.attached[cam];
  36625. if (input === inputToRemove) {
  36626. input.detachControl(this.attachedElement);
  36627. input.camera = null;
  36628. delete this.attached[cam];
  36629. this.rebuildInputCheck();
  36630. }
  36631. }
  36632. };
  36633. CameraInputsManager.prototype.removeByType = function (inputType) {
  36634. for (var cam in this.attached) {
  36635. var input = this.attached[cam];
  36636. if (input.getClassName() === inputType) {
  36637. input.detachControl(this.attachedElement);
  36638. input.camera = null;
  36639. delete this.attached[cam];
  36640. this.rebuildInputCheck();
  36641. }
  36642. }
  36643. };
  36644. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  36645. var current = this.checkInputs;
  36646. return function () {
  36647. current();
  36648. fn();
  36649. };
  36650. };
  36651. CameraInputsManager.prototype.attachInput = function (input) {
  36652. if (this.attachedElement) {
  36653. input.attachControl(this.attachedElement, this.noPreventDefault);
  36654. }
  36655. };
  36656. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  36657. if (noPreventDefault === void 0) { noPreventDefault = false; }
  36658. if (this.attachedElement) {
  36659. return;
  36660. }
  36661. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36662. this.attachedElement = element;
  36663. this.noPreventDefault = noPreventDefault;
  36664. for (var cam in this.attached) {
  36665. this.attached[cam].attachControl(element, noPreventDefault);
  36666. }
  36667. };
  36668. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  36669. if (disconnect === void 0) { disconnect = false; }
  36670. if (this.attachedElement !== element) {
  36671. return;
  36672. }
  36673. for (var cam in this.attached) {
  36674. this.attached[cam].detachControl(element);
  36675. if (disconnect) {
  36676. this.attached[cam].camera = null;
  36677. }
  36678. }
  36679. this.attachedElement = null;
  36680. };
  36681. CameraInputsManager.prototype.rebuildInputCheck = function () {
  36682. this.checkInputs = function () { };
  36683. for (var cam in this.attached) {
  36684. var input = this.attached[cam];
  36685. if (input.checkInputs) {
  36686. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36687. }
  36688. }
  36689. };
  36690. CameraInputsManager.prototype.clear = function () {
  36691. if (this.attachedElement) {
  36692. this.detachElement(this.attachedElement, true);
  36693. }
  36694. this.attached = {};
  36695. this.attachedElement = null;
  36696. this.checkInputs = function () { };
  36697. };
  36698. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  36699. var inputs = {};
  36700. for (var cam in this.attached) {
  36701. var input = this.attached[cam];
  36702. var res = BABYLON.SerializationHelper.Serialize(input);
  36703. inputs[input.getClassName()] = res;
  36704. }
  36705. serializedCamera.inputsmgr = inputs;
  36706. };
  36707. CameraInputsManager.prototype.parse = function (parsedCamera) {
  36708. var parsedInputs = parsedCamera.inputsmgr;
  36709. if (parsedInputs) {
  36710. this.clear();
  36711. for (var n in parsedInputs) {
  36712. var construct = BABYLON.CameraInputTypes[n];
  36713. if (construct) {
  36714. var parsedinput = parsedInputs[n];
  36715. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  36716. this.add(input);
  36717. }
  36718. }
  36719. }
  36720. else {
  36721. //2016-03-08 this part is for managing backward compatibility
  36722. for (var n in this.attached) {
  36723. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  36724. if (construct) {
  36725. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  36726. this.remove(this.attached[n]);
  36727. this.add(input);
  36728. }
  36729. }
  36730. }
  36731. };
  36732. return CameraInputsManager;
  36733. }());
  36734. BABYLON.CameraInputsManager = CameraInputsManager;
  36735. })(BABYLON || (BABYLON = {}));
  36736. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  36737. var BABYLON;
  36738. (function (BABYLON) {
  36739. var FreeCameraMouseInput = /** @class */ (function () {
  36740. function FreeCameraMouseInput(touchEnabled) {
  36741. if (touchEnabled === void 0) { touchEnabled = true; }
  36742. this.touchEnabled = touchEnabled;
  36743. this.buttons = [0, 1, 2];
  36744. this.angularSensibility = 2000.0;
  36745. this.previousPosition = null;
  36746. }
  36747. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  36748. var _this = this;
  36749. var engine = this.camera.getEngine();
  36750. if (!this._pointerInput) {
  36751. this._pointerInput = function (p, s) {
  36752. var evt = p.event;
  36753. if (engine.isInVRExclusivePointerMode) {
  36754. return;
  36755. }
  36756. if (!_this.touchEnabled && evt.pointerType === "touch") {
  36757. return;
  36758. }
  36759. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  36760. return;
  36761. }
  36762. var srcElement = (evt.srcElement || evt.target);
  36763. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  36764. try {
  36765. srcElement.setPointerCapture(evt.pointerId);
  36766. }
  36767. catch (e) {
  36768. //Nothing to do with the error. Execution will continue.
  36769. }
  36770. _this.previousPosition = {
  36771. x: evt.clientX,
  36772. y: evt.clientY
  36773. };
  36774. if (!noPreventDefault) {
  36775. evt.preventDefault();
  36776. element.focus();
  36777. }
  36778. }
  36779. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  36780. try {
  36781. srcElement.releasePointerCapture(evt.pointerId);
  36782. }
  36783. catch (e) {
  36784. //Nothing to do with the error.
  36785. }
  36786. _this.previousPosition = null;
  36787. if (!noPreventDefault) {
  36788. evt.preventDefault();
  36789. }
  36790. }
  36791. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  36792. if (!_this.previousPosition || engine.isPointerLock) {
  36793. return;
  36794. }
  36795. var offsetX = evt.clientX - _this.previousPosition.x;
  36796. var offsetY = evt.clientY - _this.previousPosition.y;
  36797. if (_this.camera.getScene().useRightHandedSystem) {
  36798. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  36799. }
  36800. else {
  36801. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  36802. }
  36803. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  36804. _this.previousPosition = {
  36805. x: evt.clientX,
  36806. y: evt.clientY
  36807. };
  36808. if (!noPreventDefault) {
  36809. evt.preventDefault();
  36810. }
  36811. }
  36812. };
  36813. }
  36814. this._onMouseMove = function (evt) {
  36815. if (!engine.isPointerLock) {
  36816. return;
  36817. }
  36818. if (engine.isInVRExclusivePointerMode) {
  36819. return;
  36820. }
  36821. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  36822. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  36823. if (_this.camera.getScene().useRightHandedSystem) {
  36824. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  36825. }
  36826. else {
  36827. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  36828. }
  36829. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  36830. _this.previousPosition = null;
  36831. if (!noPreventDefault) {
  36832. evt.preventDefault();
  36833. }
  36834. };
  36835. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  36836. element.addEventListener("mousemove", this._onMouseMove, false);
  36837. };
  36838. FreeCameraMouseInput.prototype.detachControl = function (element) {
  36839. if (this._observer && element) {
  36840. this.camera.getScene().onPointerObservable.remove(this._observer);
  36841. if (this._onMouseMove) {
  36842. element.removeEventListener("mousemove", this._onMouseMove);
  36843. }
  36844. this._observer = null;
  36845. this._onMouseMove = null;
  36846. this.previousPosition = null;
  36847. }
  36848. };
  36849. FreeCameraMouseInput.prototype.getClassName = function () {
  36850. return "FreeCameraMouseInput";
  36851. };
  36852. FreeCameraMouseInput.prototype.getSimpleName = function () {
  36853. return "mouse";
  36854. };
  36855. __decorate([
  36856. BABYLON.serialize()
  36857. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  36858. __decorate([
  36859. BABYLON.serialize()
  36860. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  36861. return FreeCameraMouseInput;
  36862. }());
  36863. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  36864. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  36865. })(BABYLON || (BABYLON = {}));
  36866. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  36867. var BABYLON;
  36868. (function (BABYLON) {
  36869. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  36870. function FreeCameraKeyboardMoveInput() {
  36871. this._keys = new Array();
  36872. this.keysUp = [38];
  36873. this.keysDown = [40];
  36874. this.keysLeft = [37];
  36875. this.keysRight = [39];
  36876. }
  36877. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  36878. var _this = this;
  36879. if (this._onCanvasBlurObserver) {
  36880. return;
  36881. }
  36882. this._scene = this.camera.getScene();
  36883. this._engine = this._scene.getEngine();
  36884. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  36885. _this._keys = [];
  36886. });
  36887. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  36888. var evt = info.event;
  36889. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  36890. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36891. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36892. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36893. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  36894. var index = _this._keys.indexOf(evt.keyCode);
  36895. if (index === -1) {
  36896. _this._keys.push(evt.keyCode);
  36897. }
  36898. if (!noPreventDefault) {
  36899. evt.preventDefault();
  36900. }
  36901. }
  36902. }
  36903. else {
  36904. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36905. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36906. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36907. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  36908. var index = _this._keys.indexOf(evt.keyCode);
  36909. if (index >= 0) {
  36910. _this._keys.splice(index, 1);
  36911. }
  36912. if (!noPreventDefault) {
  36913. evt.preventDefault();
  36914. }
  36915. }
  36916. }
  36917. });
  36918. };
  36919. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  36920. if (this._scene) {
  36921. if (this._onKeyboardObserver) {
  36922. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  36923. }
  36924. if (this._onCanvasBlurObserver) {
  36925. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  36926. }
  36927. this._onKeyboardObserver = null;
  36928. this._onCanvasBlurObserver = null;
  36929. }
  36930. this._keys = [];
  36931. };
  36932. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  36933. if (this._onKeyboardObserver) {
  36934. var camera = this.camera;
  36935. // Keyboard
  36936. for (var index = 0; index < this._keys.length; index++) {
  36937. var keyCode = this._keys[index];
  36938. var speed = camera._computeLocalCameraSpeed();
  36939. if (this.keysLeft.indexOf(keyCode) !== -1) {
  36940. camera._localDirection.copyFromFloats(-speed, 0, 0);
  36941. }
  36942. else if (this.keysUp.indexOf(keyCode) !== -1) {
  36943. camera._localDirection.copyFromFloats(0, 0, speed);
  36944. }
  36945. else if (this.keysRight.indexOf(keyCode) !== -1) {
  36946. camera._localDirection.copyFromFloats(speed, 0, 0);
  36947. }
  36948. else if (this.keysDown.indexOf(keyCode) !== -1) {
  36949. camera._localDirection.copyFromFloats(0, 0, -speed);
  36950. }
  36951. if (camera.getScene().useRightHandedSystem) {
  36952. camera._localDirection.z *= -1;
  36953. }
  36954. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  36955. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  36956. camera.cameraDirection.addInPlace(camera._transformedDirection);
  36957. }
  36958. }
  36959. };
  36960. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  36961. return "FreeCameraKeyboardMoveInput";
  36962. };
  36963. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  36964. this._keys = [];
  36965. };
  36966. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  36967. return "keyboard";
  36968. };
  36969. __decorate([
  36970. BABYLON.serialize()
  36971. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  36972. __decorate([
  36973. BABYLON.serialize()
  36974. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  36975. __decorate([
  36976. BABYLON.serialize()
  36977. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  36978. __decorate([
  36979. BABYLON.serialize()
  36980. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  36981. return FreeCameraKeyboardMoveInput;
  36982. }());
  36983. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  36984. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  36985. })(BABYLON || (BABYLON = {}));
  36986. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  36987. var BABYLON;
  36988. (function (BABYLON) {
  36989. var FreeCameraInputsManager = /** @class */ (function (_super) {
  36990. __extends(FreeCameraInputsManager, _super);
  36991. function FreeCameraInputsManager(camera) {
  36992. return _super.call(this, camera) || this;
  36993. }
  36994. FreeCameraInputsManager.prototype.addKeyboard = function () {
  36995. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  36996. return this;
  36997. };
  36998. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  36999. if (touchEnabled === void 0) { touchEnabled = true; }
  37000. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37001. return this;
  37002. };
  37003. FreeCameraInputsManager.prototype.addGamepad = function () {
  37004. this.add(new BABYLON.FreeCameraGamepadInput());
  37005. return this;
  37006. };
  37007. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37008. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37009. return this;
  37010. };
  37011. FreeCameraInputsManager.prototype.addTouch = function () {
  37012. this.add(new BABYLON.FreeCameraTouchInput());
  37013. return this;
  37014. };
  37015. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37016. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37017. return this;
  37018. };
  37019. return FreeCameraInputsManager;
  37020. }(BABYLON.CameraInputsManager));
  37021. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37022. })(BABYLON || (BABYLON = {}));
  37023. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37024. /// <reference path="babylon.camera.ts" />
  37025. var BABYLON;
  37026. (function (BABYLON) {
  37027. var TargetCamera = /** @class */ (function (_super) {
  37028. __extends(TargetCamera, _super);
  37029. function TargetCamera(name, position, scene) {
  37030. var _this = _super.call(this, name, position, scene) || this;
  37031. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37032. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37033. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37034. _this.speed = 2.0;
  37035. _this.noRotationConstraint = false;
  37036. _this.lockedTarget = null;
  37037. _this._currentTarget = BABYLON.Vector3.Zero();
  37038. _this._viewMatrix = BABYLON.Matrix.Zero();
  37039. _this._camMatrix = BABYLON.Matrix.Zero();
  37040. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37041. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37042. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37043. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37044. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37045. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37046. _this._tempMatrix = BABYLON.Matrix.Zero();
  37047. return _this;
  37048. }
  37049. TargetCamera.prototype.getFrontPosition = function (distance) {
  37050. var direction = this.getTarget().subtract(this.position);
  37051. direction.normalize();
  37052. direction.scaleInPlace(distance);
  37053. return this.globalPosition.add(direction);
  37054. };
  37055. TargetCamera.prototype._getLockedTargetPosition = function () {
  37056. if (!this.lockedTarget) {
  37057. return null;
  37058. }
  37059. if (this.lockedTarget.absolutePosition) {
  37060. this.lockedTarget.computeWorldMatrix();
  37061. }
  37062. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37063. };
  37064. TargetCamera.prototype.storeState = function () {
  37065. this._storedPosition = this.position.clone();
  37066. this._storedRotation = this.rotation.clone();
  37067. if (this.rotationQuaternion) {
  37068. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37069. }
  37070. return _super.prototype.storeState.call(this);
  37071. };
  37072. /**
  37073. * Restored camera state. You must call storeState() first
  37074. */
  37075. TargetCamera.prototype._restoreStateValues = function () {
  37076. if (!_super.prototype._restoreStateValues.call(this)) {
  37077. return false;
  37078. }
  37079. this.position = this._storedPosition.clone();
  37080. this.rotation = this._storedRotation.clone();
  37081. if (this.rotationQuaternion) {
  37082. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37083. }
  37084. this.cameraDirection.copyFromFloats(0, 0, 0);
  37085. this.cameraRotation.copyFromFloats(0, 0);
  37086. return true;
  37087. };
  37088. // Cache
  37089. TargetCamera.prototype._initCache = function () {
  37090. _super.prototype._initCache.call(this);
  37091. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37092. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37093. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37094. };
  37095. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37096. if (!ignoreParentClass) {
  37097. _super.prototype._updateCache.call(this);
  37098. }
  37099. var lockedTargetPosition = this._getLockedTargetPosition();
  37100. if (!lockedTargetPosition) {
  37101. this._cache.lockedTarget = null;
  37102. }
  37103. else {
  37104. if (!this._cache.lockedTarget) {
  37105. this._cache.lockedTarget = lockedTargetPosition.clone();
  37106. }
  37107. else {
  37108. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37109. }
  37110. }
  37111. this._cache.rotation.copyFrom(this.rotation);
  37112. if (this.rotationQuaternion)
  37113. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37114. };
  37115. // Synchronized
  37116. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37117. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37118. return false;
  37119. }
  37120. var lockedTargetPosition = this._getLockedTargetPosition();
  37121. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37122. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37123. };
  37124. // Methods
  37125. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37126. var engine = this.getEngine();
  37127. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37128. };
  37129. // Target
  37130. TargetCamera.prototype.setTarget = function (target) {
  37131. this.upVector.normalize();
  37132. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37133. this._camMatrix.invert();
  37134. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37135. var vDir = target.subtract(this.position);
  37136. if (vDir.x >= 0.0) {
  37137. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37138. }
  37139. else {
  37140. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37141. }
  37142. this.rotation.z = 0;
  37143. if (isNaN(this.rotation.x)) {
  37144. this.rotation.x = 0;
  37145. }
  37146. if (isNaN(this.rotation.y)) {
  37147. this.rotation.y = 0;
  37148. }
  37149. if (isNaN(this.rotation.z)) {
  37150. this.rotation.z = 0;
  37151. }
  37152. if (this.rotationQuaternion) {
  37153. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37154. }
  37155. };
  37156. /**
  37157. * Return the current target position of the camera. This value is expressed in local space.
  37158. */
  37159. TargetCamera.prototype.getTarget = function () {
  37160. return this._currentTarget;
  37161. };
  37162. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37163. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37164. };
  37165. TargetCamera.prototype._updatePosition = function () {
  37166. if (this.parent) {
  37167. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37168. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37169. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37170. return;
  37171. }
  37172. this.position.addInPlace(this.cameraDirection);
  37173. };
  37174. TargetCamera.prototype._checkInputs = function () {
  37175. var needToMove = this._decideIfNeedsToMove();
  37176. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37177. // Move
  37178. if (needToMove) {
  37179. this._updatePosition();
  37180. }
  37181. // Rotate
  37182. if (needToRotate) {
  37183. this.rotation.x += this.cameraRotation.x;
  37184. this.rotation.y += this.cameraRotation.y;
  37185. //rotate, if quaternion is set and rotation was used
  37186. if (this.rotationQuaternion) {
  37187. var len = this.rotation.lengthSquared();
  37188. if (len) {
  37189. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37190. }
  37191. }
  37192. if (!this.noRotationConstraint) {
  37193. var limit = (Math.PI / 2) * 0.95;
  37194. if (this.rotation.x > limit)
  37195. this.rotation.x = limit;
  37196. if (this.rotation.x < -limit)
  37197. this.rotation.x = -limit;
  37198. }
  37199. }
  37200. // Inertia
  37201. if (needToMove) {
  37202. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37203. this.cameraDirection.x = 0;
  37204. }
  37205. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37206. this.cameraDirection.y = 0;
  37207. }
  37208. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37209. this.cameraDirection.z = 0;
  37210. }
  37211. this.cameraDirection.scaleInPlace(this.inertia);
  37212. }
  37213. if (needToRotate) {
  37214. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37215. this.cameraRotation.x = 0;
  37216. }
  37217. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37218. this.cameraRotation.y = 0;
  37219. }
  37220. this.cameraRotation.scaleInPlace(this.inertia);
  37221. }
  37222. _super.prototype._checkInputs.call(this);
  37223. };
  37224. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37225. if (this.rotationQuaternion) {
  37226. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37227. }
  37228. else {
  37229. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37230. }
  37231. //update the up vector!
  37232. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37233. };
  37234. TargetCamera.prototype._getViewMatrix = function () {
  37235. if (!this.lockedTarget) {
  37236. // Compute
  37237. this._updateCameraRotationMatrix();
  37238. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37239. // Computing target and final matrix
  37240. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37241. }
  37242. else {
  37243. var targetPosition = this._getLockedTargetPosition();
  37244. if (targetPosition) {
  37245. this._currentTarget.copyFrom(targetPosition);
  37246. }
  37247. }
  37248. if (this.getScene().useRightHandedSystem) {
  37249. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37250. }
  37251. else {
  37252. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37253. }
  37254. return this._viewMatrix;
  37255. };
  37256. /**
  37257. * @override
  37258. * Override Camera.createRigCamera
  37259. */
  37260. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37261. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37262. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37263. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37264. if (!this.rotationQuaternion) {
  37265. this.rotationQuaternion = new BABYLON.Quaternion();
  37266. }
  37267. rigCamera._cameraRigParams = {};
  37268. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37269. }
  37270. return rigCamera;
  37271. }
  37272. return null;
  37273. };
  37274. /**
  37275. * @override
  37276. * Override Camera._updateRigCameras
  37277. */
  37278. TargetCamera.prototype._updateRigCameras = function () {
  37279. var camLeft = this._rigCameras[0];
  37280. var camRight = this._rigCameras[1];
  37281. switch (this.cameraRigMode) {
  37282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37283. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37284. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37285. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37286. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37287. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37288. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37289. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37290. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37291. camLeft.setTarget(this.getTarget());
  37292. camRight.setTarget(this.getTarget());
  37293. break;
  37294. case BABYLON.Camera.RIG_MODE_VR:
  37295. if (camLeft.rotationQuaternion) {
  37296. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37297. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37298. }
  37299. else {
  37300. camLeft.rotation.copyFrom(this.rotation);
  37301. camRight.rotation.copyFrom(this.rotation);
  37302. }
  37303. camLeft.position.copyFrom(this.position);
  37304. camRight.position.copyFrom(this.position);
  37305. break;
  37306. }
  37307. _super.prototype._updateRigCameras.call(this);
  37308. };
  37309. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37310. if (!this._rigCamTransformMatrix) {
  37311. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37312. }
  37313. var target = this.getTarget();
  37314. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37315. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37316. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37317. };
  37318. TargetCamera.prototype.getClassName = function () {
  37319. return "TargetCamera";
  37320. };
  37321. __decorate([
  37322. BABYLON.serializeAsVector3()
  37323. ], TargetCamera.prototype, "rotation", void 0);
  37324. __decorate([
  37325. BABYLON.serialize()
  37326. ], TargetCamera.prototype, "speed", void 0);
  37327. __decorate([
  37328. BABYLON.serializeAsMeshReference("lockedTargetId")
  37329. ], TargetCamera.prototype, "lockedTarget", void 0);
  37330. return TargetCamera;
  37331. }(BABYLON.Camera));
  37332. BABYLON.TargetCamera = TargetCamera;
  37333. })(BABYLON || (BABYLON = {}));
  37334. //# sourceMappingURL=babylon.targetCamera.js.map
  37335. var BABYLON;
  37336. (function (BABYLON) {
  37337. var FreeCamera = /** @class */ (function (_super) {
  37338. __extends(FreeCamera, _super);
  37339. function FreeCamera(name, position, scene) {
  37340. var _this = _super.call(this, name, position, scene) || this;
  37341. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37342. _this.checkCollisions = false;
  37343. _this.applyGravity = false;
  37344. _this._needMoveForGravity = false;
  37345. _this._oldPosition = BABYLON.Vector3.Zero();
  37346. _this._diffPosition = BABYLON.Vector3.Zero();
  37347. _this._newPosition = BABYLON.Vector3.Zero();
  37348. // Collisions
  37349. _this._collisionMask = -1;
  37350. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37351. if (collidedMesh === void 0) { collidedMesh = null; }
  37352. //TODO move this to the collision coordinator!
  37353. if (_this.getScene().workerCollisions)
  37354. newPosition.multiplyInPlace(_this._collider.radius);
  37355. var updatePosition = function (newPos) {
  37356. _this._newPosition.copyFrom(newPos);
  37357. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37358. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37359. _this.position.addInPlace(_this._diffPosition);
  37360. if (_this.onCollide && collidedMesh) {
  37361. _this.onCollide(collidedMesh);
  37362. }
  37363. }
  37364. };
  37365. updatePosition(newPosition);
  37366. };
  37367. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37368. _this.inputs.addKeyboard().addMouse();
  37369. return _this;
  37370. }
  37371. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37372. //-- begin properties for backward compatibility for inputs
  37373. get: function () {
  37374. var mouse = this.inputs.attached["mouse"];
  37375. if (mouse)
  37376. return mouse.angularSensibility;
  37377. return 0;
  37378. },
  37379. set: function (value) {
  37380. var mouse = this.inputs.attached["mouse"];
  37381. if (mouse)
  37382. mouse.angularSensibility = value;
  37383. },
  37384. enumerable: true,
  37385. configurable: true
  37386. });
  37387. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37388. get: function () {
  37389. var keyboard = this.inputs.attached["keyboard"];
  37390. if (keyboard)
  37391. return keyboard.keysUp;
  37392. return [];
  37393. },
  37394. set: function (value) {
  37395. var keyboard = this.inputs.attached["keyboard"];
  37396. if (keyboard)
  37397. keyboard.keysUp = value;
  37398. },
  37399. enumerable: true,
  37400. configurable: true
  37401. });
  37402. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37403. get: function () {
  37404. var keyboard = this.inputs.attached["keyboard"];
  37405. if (keyboard)
  37406. return keyboard.keysDown;
  37407. return [];
  37408. },
  37409. set: function (value) {
  37410. var keyboard = this.inputs.attached["keyboard"];
  37411. if (keyboard)
  37412. keyboard.keysDown = value;
  37413. },
  37414. enumerable: true,
  37415. configurable: true
  37416. });
  37417. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37418. get: function () {
  37419. var keyboard = this.inputs.attached["keyboard"];
  37420. if (keyboard)
  37421. return keyboard.keysLeft;
  37422. return [];
  37423. },
  37424. set: function (value) {
  37425. var keyboard = this.inputs.attached["keyboard"];
  37426. if (keyboard)
  37427. keyboard.keysLeft = value;
  37428. },
  37429. enumerable: true,
  37430. configurable: true
  37431. });
  37432. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37433. get: function () {
  37434. var keyboard = this.inputs.attached["keyboard"];
  37435. if (keyboard)
  37436. return keyboard.keysRight;
  37437. return [];
  37438. },
  37439. set: function (value) {
  37440. var keyboard = this.inputs.attached["keyboard"];
  37441. if (keyboard)
  37442. keyboard.keysRight = value;
  37443. },
  37444. enumerable: true,
  37445. configurable: true
  37446. });
  37447. // Controls
  37448. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37449. this.inputs.attachElement(element, noPreventDefault);
  37450. };
  37451. FreeCamera.prototype.detachControl = function (element) {
  37452. this.inputs.detachElement(element);
  37453. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37454. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37455. };
  37456. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37457. get: function () {
  37458. return this._collisionMask;
  37459. },
  37460. set: function (mask) {
  37461. this._collisionMask = !isNaN(mask) ? mask : -1;
  37462. },
  37463. enumerable: true,
  37464. configurable: true
  37465. });
  37466. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37467. var globalPosition;
  37468. if (this.parent) {
  37469. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37470. }
  37471. else {
  37472. globalPosition = this.position;
  37473. }
  37474. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37475. if (!this._collider) {
  37476. this._collider = new BABYLON.Collider();
  37477. }
  37478. this._collider.radius = this.ellipsoid;
  37479. this._collider.collisionMask = this._collisionMask;
  37480. //no need for clone, as long as gravity is not on.
  37481. var actualDisplacement = displacement;
  37482. //add gravity to the direction to prevent the dual-collision checking
  37483. if (this.applyGravity) {
  37484. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37485. actualDisplacement = displacement.add(this.getScene().gravity);
  37486. }
  37487. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37488. };
  37489. FreeCamera.prototype._checkInputs = function () {
  37490. if (!this._localDirection) {
  37491. this._localDirection = BABYLON.Vector3.Zero();
  37492. this._transformedDirection = BABYLON.Vector3.Zero();
  37493. }
  37494. this.inputs.checkInputs();
  37495. _super.prototype._checkInputs.call(this);
  37496. };
  37497. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37498. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37499. };
  37500. FreeCamera.prototype._updatePosition = function () {
  37501. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37502. this._collideWithWorld(this.cameraDirection);
  37503. }
  37504. else {
  37505. _super.prototype._updatePosition.call(this);
  37506. }
  37507. };
  37508. FreeCamera.prototype.dispose = function () {
  37509. this.inputs.clear();
  37510. _super.prototype.dispose.call(this);
  37511. };
  37512. FreeCamera.prototype.getClassName = function () {
  37513. return "FreeCamera";
  37514. };
  37515. __decorate([
  37516. BABYLON.serializeAsVector3()
  37517. ], FreeCamera.prototype, "ellipsoid", void 0);
  37518. __decorate([
  37519. BABYLON.serialize()
  37520. ], FreeCamera.prototype, "checkCollisions", void 0);
  37521. __decorate([
  37522. BABYLON.serialize()
  37523. ], FreeCamera.prototype, "applyGravity", void 0);
  37524. return FreeCamera;
  37525. }(BABYLON.TargetCamera));
  37526. BABYLON.FreeCamera = FreeCamera;
  37527. })(BABYLON || (BABYLON = {}));
  37528. //# sourceMappingURL=babylon.freeCamera.js.map
  37529. var BABYLON;
  37530. (function (BABYLON) {
  37531. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37532. function ArcRotateCameraKeyboardMoveInput() {
  37533. this._keys = new Array();
  37534. this.keysUp = [38];
  37535. this.keysDown = [40];
  37536. this.keysLeft = [37];
  37537. this.keysRight = [39];
  37538. this.keysReset = [220];
  37539. this.panningSensibility = 50.0;
  37540. this.zoomingSensibility = 25.0;
  37541. this.useAltToZoom = true;
  37542. }
  37543. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37544. var _this = this;
  37545. if (this._onCanvasBlurObserver) {
  37546. return;
  37547. }
  37548. this._scene = this.camera.getScene();
  37549. this._engine = this._scene.getEngine();
  37550. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37551. _this._keys = [];
  37552. });
  37553. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37554. var evt = info.event;
  37555. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37556. _this._ctrlPressed = evt.ctrlKey;
  37557. _this._altPressed = evt.altKey;
  37558. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37559. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37560. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37561. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37562. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37563. var index = _this._keys.indexOf(evt.keyCode);
  37564. if (index === -1) {
  37565. _this._keys.push(evt.keyCode);
  37566. }
  37567. if (evt.preventDefault) {
  37568. if (!noPreventDefault) {
  37569. evt.preventDefault();
  37570. }
  37571. }
  37572. }
  37573. }
  37574. else {
  37575. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37576. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37577. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37578. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37579. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37580. var index = _this._keys.indexOf(evt.keyCode);
  37581. if (index >= 0) {
  37582. _this._keys.splice(index, 1);
  37583. }
  37584. if (evt.preventDefault) {
  37585. if (!noPreventDefault) {
  37586. evt.preventDefault();
  37587. }
  37588. }
  37589. }
  37590. }
  37591. });
  37592. };
  37593. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37594. if (this._scene) {
  37595. if (this._onKeyboardObserver) {
  37596. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37597. }
  37598. if (this._onCanvasBlurObserver) {
  37599. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37600. }
  37601. this._onKeyboardObserver = null;
  37602. this._onCanvasBlurObserver = null;
  37603. }
  37604. this._keys = [];
  37605. };
  37606. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37607. if (this._onKeyboardObserver) {
  37608. var camera = this.camera;
  37609. for (var index = 0; index < this._keys.length; index++) {
  37610. var keyCode = this._keys[index];
  37611. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37612. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37613. camera.inertialPanningX -= 1 / this.panningSensibility;
  37614. }
  37615. else {
  37616. camera.inertialAlphaOffset -= 0.01;
  37617. }
  37618. }
  37619. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37620. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37621. camera.inertialPanningY += 1 / this.panningSensibility;
  37622. }
  37623. else if (this._altPressed && this.useAltToZoom) {
  37624. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  37625. }
  37626. else {
  37627. camera.inertialBetaOffset -= 0.01;
  37628. }
  37629. }
  37630. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37631. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37632. camera.inertialPanningX += 1 / this.panningSensibility;
  37633. }
  37634. else {
  37635. camera.inertialAlphaOffset += 0.01;
  37636. }
  37637. }
  37638. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37639. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37640. camera.inertialPanningY -= 1 / this.panningSensibility;
  37641. }
  37642. else if (this._altPressed && this.useAltToZoom) {
  37643. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  37644. }
  37645. else {
  37646. camera.inertialBetaOffset += 0.01;
  37647. }
  37648. }
  37649. else if (this.keysReset.indexOf(keyCode) !== -1) {
  37650. camera.restoreState();
  37651. }
  37652. }
  37653. }
  37654. };
  37655. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  37656. return "ArcRotateCameraKeyboardMoveInput";
  37657. };
  37658. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37659. return "keyboard";
  37660. };
  37661. __decorate([
  37662. BABYLON.serialize()
  37663. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37664. __decorate([
  37665. BABYLON.serialize()
  37666. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37667. __decorate([
  37668. BABYLON.serialize()
  37669. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37670. __decorate([
  37671. BABYLON.serialize()
  37672. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37673. __decorate([
  37674. BABYLON.serialize()
  37675. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  37676. __decorate([
  37677. BABYLON.serialize()
  37678. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  37679. __decorate([
  37680. BABYLON.serialize()
  37681. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  37682. __decorate([
  37683. BABYLON.serialize()
  37684. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  37685. return ArcRotateCameraKeyboardMoveInput;
  37686. }());
  37687. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  37688. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  37689. })(BABYLON || (BABYLON = {}));
  37690. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  37691. var BABYLON;
  37692. (function (BABYLON) {
  37693. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  37694. function ArcRotateCameraMouseWheelInput() {
  37695. this.wheelPrecision = 3.0;
  37696. /**
  37697. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  37698. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  37699. */
  37700. this.wheelDeltaPercentage = 0;
  37701. }
  37702. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  37703. var _this = this;
  37704. this._wheel = function (p, s) {
  37705. //sanity check - this should be a PointerWheel event.
  37706. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  37707. return;
  37708. var event = p.event;
  37709. var delta = 0;
  37710. if (event.wheelDelta) {
  37711. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  37712. }
  37713. else if (event.detail) {
  37714. delta = -event.detail / _this.wheelPrecision;
  37715. }
  37716. if (delta)
  37717. _this.camera.inertialRadiusOffset += delta;
  37718. if (event.preventDefault) {
  37719. if (!noPreventDefault) {
  37720. event.preventDefault();
  37721. }
  37722. }
  37723. };
  37724. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  37725. };
  37726. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  37727. if (this._observer && element) {
  37728. this.camera.getScene().onPointerObservable.remove(this._observer);
  37729. this._observer = null;
  37730. this._wheel = null;
  37731. }
  37732. };
  37733. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  37734. return "ArcRotateCameraMouseWheelInput";
  37735. };
  37736. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  37737. return "mousewheel";
  37738. };
  37739. __decorate([
  37740. BABYLON.serialize()
  37741. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  37742. __decorate([
  37743. BABYLON.serialize()
  37744. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  37745. return ArcRotateCameraMouseWheelInput;
  37746. }());
  37747. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  37748. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  37749. })(BABYLON || (BABYLON = {}));
  37750. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  37751. var BABYLON;
  37752. (function (BABYLON) {
  37753. var ArcRotateCameraPointersInput = /** @class */ (function () {
  37754. function ArcRotateCameraPointersInput() {
  37755. this.buttons = [0, 1, 2];
  37756. this.angularSensibilityX = 1000.0;
  37757. this.angularSensibilityY = 1000.0;
  37758. this.pinchPrecision = 12.0;
  37759. /**
  37760. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  37761. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  37762. */
  37763. this.pinchDeltaPercentage = 0;
  37764. this.panningSensibility = 1000.0;
  37765. this.multiTouchPanning = true;
  37766. this.multiTouchPanAndZoom = true;
  37767. this._isPanClick = false;
  37768. this.pinchInwards = true;
  37769. }
  37770. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  37771. var _this = this;
  37772. var engine = this.camera.getEngine();
  37773. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  37774. var pointA = null;
  37775. var pointB = null;
  37776. var previousPinchSquaredDistance = 0;
  37777. var initialDistance = 0;
  37778. var twoFingerActivityCount = 0;
  37779. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  37780. this._pointerInput = function (p, s) {
  37781. var evt = p.event;
  37782. if (engine.isInVRExclusivePointerMode) {
  37783. return;
  37784. }
  37785. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37786. return;
  37787. }
  37788. var srcElement = (evt.srcElement || evt.target);
  37789. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37790. try {
  37791. srcElement.setPointerCapture(evt.pointerId);
  37792. }
  37793. catch (e) {
  37794. //Nothing to do with the error. Execution will continue.
  37795. }
  37796. // Manage panning with pan button click
  37797. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  37798. // manage pointers
  37799. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  37800. if (pointA === null) {
  37801. pointA = cacheSoloPointer;
  37802. }
  37803. else if (pointB === null) {
  37804. pointB = cacheSoloPointer;
  37805. }
  37806. if (!noPreventDefault) {
  37807. evt.preventDefault();
  37808. element.focus();
  37809. }
  37810. }
  37811. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  37812. _this.camera.restoreState();
  37813. }
  37814. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37815. try {
  37816. srcElement.releasePointerCapture(evt.pointerId);
  37817. }
  37818. catch (e) {
  37819. //Nothing to do with the error.
  37820. }
  37821. cacheSoloPointer = null;
  37822. previousPinchSquaredDistance = 0;
  37823. previousMultiTouchPanPosition.isPaning = false;
  37824. previousMultiTouchPanPosition.isPinching = false;
  37825. twoFingerActivityCount = 0;
  37826. initialDistance = 0;
  37827. if (p.event.pointerType !== "touch") {
  37828. pointB = null; // Mouse and pen are mono pointer
  37829. }
  37830. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  37831. //but emptying completly pointers collection is required to fix a bug on iPhone :
  37832. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  37833. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  37834. if (engine.badOS) {
  37835. pointA = pointB = null;
  37836. }
  37837. else {
  37838. //only remove the impacted pointer in case of multitouch allowing on most
  37839. //platforms switching from rotate to zoom and pan seamlessly.
  37840. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  37841. pointA = pointB;
  37842. pointB = null;
  37843. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  37844. }
  37845. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  37846. pointB = null;
  37847. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  37848. }
  37849. else {
  37850. pointA = pointB = null;
  37851. }
  37852. }
  37853. if (!noPreventDefault) {
  37854. evt.preventDefault();
  37855. }
  37856. }
  37857. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37858. if (!noPreventDefault) {
  37859. evt.preventDefault();
  37860. }
  37861. // One button down
  37862. if (pointA && pointB === null && cacheSoloPointer) {
  37863. if (_this.panningSensibility !== 0 &&
  37864. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  37865. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  37866. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  37867. }
  37868. else {
  37869. var offsetX = evt.clientX - cacheSoloPointer.x;
  37870. var offsetY = evt.clientY - cacheSoloPointer.y;
  37871. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  37872. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  37873. }
  37874. cacheSoloPointer.x = evt.clientX;
  37875. cacheSoloPointer.y = evt.clientY;
  37876. }
  37877. else if (pointA && pointB) {
  37878. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  37879. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  37880. ed.x = evt.clientX;
  37881. ed.y = evt.clientY;
  37882. var direction = _this.pinchInwards ? 1 : -1;
  37883. var distX = pointA.x - pointB.x;
  37884. var distY = pointA.y - pointB.y;
  37885. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  37886. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  37887. if (previousPinchSquaredDistance === 0) {
  37888. initialDistance = pinchDistance;
  37889. previousPinchSquaredDistance = pinchSquaredDistance;
  37890. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  37891. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  37892. return;
  37893. }
  37894. if (_this.multiTouchPanAndZoom) {
  37895. if (_this.pinchDeltaPercentage) {
  37896. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  37897. }
  37898. else {
  37899. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  37900. (_this.pinchPrecision *
  37901. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  37902. direction);
  37903. }
  37904. if (_this.panningSensibility !== 0) {
  37905. var pointersCenterX = (pointA.x + pointB.x) / 2;
  37906. var pointersCenterY = (pointA.y + pointB.y) / 2;
  37907. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  37908. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  37909. previousMultiTouchPanPosition.x = pointersCenterX;
  37910. previousMultiTouchPanPosition.y = pointersCenterY;
  37911. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  37912. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  37913. }
  37914. }
  37915. else {
  37916. twoFingerActivityCount++;
  37917. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  37918. if (_this.pinchDeltaPercentage) {
  37919. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  37920. }
  37921. else {
  37922. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  37923. (_this.pinchPrecision *
  37924. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  37925. direction);
  37926. }
  37927. previousMultiTouchPanPosition.isPaning = false;
  37928. previousMultiTouchPanPosition.isPinching = true;
  37929. }
  37930. else {
  37931. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  37932. if (!previousMultiTouchPanPosition.isPaning) {
  37933. previousMultiTouchPanPosition.isPaning = true;
  37934. previousMultiTouchPanPosition.isPinching = false;
  37935. previousMultiTouchPanPosition.x = ed.x;
  37936. previousMultiTouchPanPosition.y = ed.y;
  37937. return;
  37938. }
  37939. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  37940. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  37941. }
  37942. }
  37943. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  37944. previousMultiTouchPanPosition.x = ed.x;
  37945. previousMultiTouchPanPosition.y = ed.y;
  37946. }
  37947. }
  37948. previousPinchSquaredDistance = pinchSquaredDistance;
  37949. }
  37950. }
  37951. };
  37952. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  37953. this._onContextMenu = function (evt) {
  37954. evt.preventDefault();
  37955. };
  37956. if (!this.camera._useCtrlForPanning) {
  37957. element.addEventListener("contextmenu", this._onContextMenu, false);
  37958. }
  37959. this._onLostFocus = function () {
  37960. //this._keys = [];
  37961. pointA = pointB = null;
  37962. previousPinchSquaredDistance = 0;
  37963. previousMultiTouchPanPosition.isPaning = false;
  37964. previousMultiTouchPanPosition.isPinching = false;
  37965. twoFingerActivityCount = 0;
  37966. cacheSoloPointer = null;
  37967. initialDistance = 0;
  37968. };
  37969. this._onMouseMove = function (evt) {
  37970. if (!engine.isPointerLock) {
  37971. return;
  37972. }
  37973. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37974. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37975. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  37976. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  37977. if (!noPreventDefault) {
  37978. evt.preventDefault();
  37979. }
  37980. };
  37981. this._onGestureStart = function (e) {
  37982. if (window.MSGesture === undefined) {
  37983. return;
  37984. }
  37985. if (!_this._MSGestureHandler) {
  37986. _this._MSGestureHandler = new MSGesture();
  37987. _this._MSGestureHandler.target = element;
  37988. }
  37989. _this._MSGestureHandler.addPointer(e.pointerId);
  37990. };
  37991. this._onGesture = function (e) {
  37992. _this.camera.radius *= e.scale;
  37993. if (e.preventDefault) {
  37994. if (!noPreventDefault) {
  37995. e.stopPropagation();
  37996. e.preventDefault();
  37997. }
  37998. }
  37999. };
  38000. element.addEventListener("mousemove", this._onMouseMove, false);
  38001. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38002. element.addEventListener("MSGestureChange", this._onGesture, false);
  38003. BABYLON.Tools.RegisterTopRootEvents([
  38004. { name: "blur", handler: this._onLostFocus }
  38005. ]);
  38006. };
  38007. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38008. if (this._onLostFocus) {
  38009. BABYLON.Tools.UnregisterTopRootEvents([
  38010. { name: "blur", handler: this._onLostFocus }
  38011. ]);
  38012. }
  38013. if (element && this._observer) {
  38014. this.camera.getScene().onPointerObservable.remove(this._observer);
  38015. this._observer = null;
  38016. if (this._onContextMenu) {
  38017. element.removeEventListener("contextmenu", this._onContextMenu);
  38018. }
  38019. if (this._onMouseMove) {
  38020. element.removeEventListener("mousemove", this._onMouseMove);
  38021. }
  38022. if (this._onGestureStart) {
  38023. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38024. }
  38025. if (this._onGesture) {
  38026. element.removeEventListener("MSGestureChange", this._onGesture);
  38027. }
  38028. this._isPanClick = false;
  38029. this.pinchInwards = true;
  38030. this._onMouseMove = null;
  38031. this._onGestureStart = null;
  38032. this._onGesture = null;
  38033. this._MSGestureHandler = null;
  38034. this._onLostFocus = null;
  38035. this._onContextMenu = null;
  38036. }
  38037. };
  38038. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38039. return "ArcRotateCameraPointersInput";
  38040. };
  38041. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38042. return "pointers";
  38043. };
  38044. __decorate([
  38045. BABYLON.serialize()
  38046. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38047. __decorate([
  38048. BABYLON.serialize()
  38049. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38050. __decorate([
  38051. BABYLON.serialize()
  38052. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38053. __decorate([
  38054. BABYLON.serialize()
  38055. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38056. __decorate([
  38057. BABYLON.serialize()
  38058. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38059. __decorate([
  38060. BABYLON.serialize()
  38061. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38062. __decorate([
  38063. BABYLON.serialize()
  38064. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38065. __decorate([
  38066. BABYLON.serialize()
  38067. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38068. return ArcRotateCameraPointersInput;
  38069. }());
  38070. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38071. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38072. })(BABYLON || (BABYLON = {}));
  38073. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38074. /// <reference path="babylon.targetCamera.ts" />
  38075. /// <reference path="..\Tools\babylon.tools.ts" />
  38076. var BABYLON;
  38077. (function (BABYLON) {
  38078. var ArcRotateCamera = /** @class */ (function (_super) {
  38079. __extends(ArcRotateCamera, _super);
  38080. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38081. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38082. _this.inertialAlphaOffset = 0;
  38083. _this.inertialBetaOffset = 0;
  38084. _this.inertialRadiusOffset = 0;
  38085. _this.lowerAlphaLimit = null;
  38086. _this.upperAlphaLimit = null;
  38087. _this.lowerBetaLimit = 0.01;
  38088. _this.upperBetaLimit = Math.PI;
  38089. _this.lowerRadiusLimit = null;
  38090. _this.upperRadiusLimit = null;
  38091. _this.inertialPanningX = 0;
  38092. _this.inertialPanningY = 0;
  38093. _this.pinchToPanMaxDistance = 20;
  38094. _this.panningDistanceLimit = null;
  38095. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38096. _this.panningInertia = 0.9;
  38097. //-- end properties for backward compatibility for inputs
  38098. _this.zoomOnFactor = 1;
  38099. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38100. _this.allowUpsideDown = true;
  38101. _this._viewMatrix = new BABYLON.Matrix();
  38102. // Panning
  38103. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38104. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38105. _this.checkCollisions = false;
  38106. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38107. _this._previousPosition = BABYLON.Vector3.Zero();
  38108. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38109. _this._newPosition = BABYLON.Vector3.Zero();
  38110. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38111. if (collidedMesh === void 0) { collidedMesh = null; }
  38112. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38113. newPosition.multiplyInPlace(_this._collider.radius);
  38114. }
  38115. if (!collidedMesh) {
  38116. _this._previousPosition.copyFrom(_this.position);
  38117. }
  38118. else {
  38119. _this.setPosition(newPosition);
  38120. if (_this.onCollide) {
  38121. _this.onCollide(collidedMesh);
  38122. }
  38123. }
  38124. // Recompute because of constraints
  38125. var cosa = Math.cos(_this.alpha);
  38126. var sina = Math.sin(_this.alpha);
  38127. var cosb = Math.cos(_this.beta);
  38128. var sinb = Math.sin(_this.beta);
  38129. if (sinb === 0) {
  38130. sinb = 0.0001;
  38131. }
  38132. var target = _this._getTargetPosition();
  38133. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38134. _this.position.copyFrom(_this._newPosition);
  38135. var up = _this.upVector;
  38136. if (_this.allowUpsideDown && _this.beta < 0) {
  38137. up = up.clone();
  38138. up = up.negate();
  38139. }
  38140. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38141. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38142. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38143. _this._collisionTriggered = false;
  38144. };
  38145. _this._target = BABYLON.Vector3.Zero();
  38146. if (target) {
  38147. _this.setTarget(target);
  38148. }
  38149. _this.alpha = alpha;
  38150. _this.beta = beta;
  38151. _this.radius = radius;
  38152. _this.getViewMatrix();
  38153. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38154. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38155. return _this;
  38156. }
  38157. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38158. get: function () {
  38159. return this._target;
  38160. },
  38161. set: function (value) {
  38162. this.setTarget(value);
  38163. },
  38164. enumerable: true,
  38165. configurable: true
  38166. });
  38167. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38168. //-- begin properties for backward compatibility for inputs
  38169. get: function () {
  38170. var pointers = this.inputs.attached["pointers"];
  38171. if (pointers)
  38172. return pointers.angularSensibilityX;
  38173. return 0;
  38174. },
  38175. set: function (value) {
  38176. var pointers = this.inputs.attached["pointers"];
  38177. if (pointers) {
  38178. pointers.angularSensibilityX = value;
  38179. }
  38180. },
  38181. enumerable: true,
  38182. configurable: true
  38183. });
  38184. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38185. get: function () {
  38186. var pointers = this.inputs.attached["pointers"];
  38187. if (pointers)
  38188. return pointers.angularSensibilityY;
  38189. return 0;
  38190. },
  38191. set: function (value) {
  38192. var pointers = this.inputs.attached["pointers"];
  38193. if (pointers) {
  38194. pointers.angularSensibilityY = value;
  38195. }
  38196. },
  38197. enumerable: true,
  38198. configurable: true
  38199. });
  38200. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38201. get: function () {
  38202. var pointers = this.inputs.attached["pointers"];
  38203. if (pointers)
  38204. return pointers.pinchPrecision;
  38205. return 0;
  38206. },
  38207. set: function (value) {
  38208. var pointers = this.inputs.attached["pointers"];
  38209. if (pointers) {
  38210. pointers.pinchPrecision = value;
  38211. }
  38212. },
  38213. enumerable: true,
  38214. configurable: true
  38215. });
  38216. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38217. get: function () {
  38218. var pointers = this.inputs.attached["pointers"];
  38219. if (pointers)
  38220. return pointers.pinchDeltaPercentage;
  38221. return 0;
  38222. },
  38223. set: function (value) {
  38224. var pointers = this.inputs.attached["pointers"];
  38225. if (pointers) {
  38226. pointers.pinchDeltaPercentage = value;
  38227. }
  38228. },
  38229. enumerable: true,
  38230. configurable: true
  38231. });
  38232. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38233. get: function () {
  38234. var pointers = this.inputs.attached["pointers"];
  38235. if (pointers)
  38236. return pointers.panningSensibility;
  38237. return 0;
  38238. },
  38239. set: function (value) {
  38240. var pointers = this.inputs.attached["pointers"];
  38241. if (pointers) {
  38242. pointers.panningSensibility = value;
  38243. }
  38244. },
  38245. enumerable: true,
  38246. configurable: true
  38247. });
  38248. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38249. get: function () {
  38250. var keyboard = this.inputs.attached["keyboard"];
  38251. if (keyboard)
  38252. return keyboard.keysUp;
  38253. return [];
  38254. },
  38255. set: function (value) {
  38256. var keyboard = this.inputs.attached["keyboard"];
  38257. if (keyboard)
  38258. keyboard.keysUp = value;
  38259. },
  38260. enumerable: true,
  38261. configurable: true
  38262. });
  38263. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38264. get: function () {
  38265. var keyboard = this.inputs.attached["keyboard"];
  38266. if (keyboard)
  38267. return keyboard.keysDown;
  38268. return [];
  38269. },
  38270. set: function (value) {
  38271. var keyboard = this.inputs.attached["keyboard"];
  38272. if (keyboard)
  38273. keyboard.keysDown = value;
  38274. },
  38275. enumerable: true,
  38276. configurable: true
  38277. });
  38278. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38279. get: function () {
  38280. var keyboard = this.inputs.attached["keyboard"];
  38281. if (keyboard)
  38282. return keyboard.keysLeft;
  38283. return [];
  38284. },
  38285. set: function (value) {
  38286. var keyboard = this.inputs.attached["keyboard"];
  38287. if (keyboard)
  38288. keyboard.keysLeft = value;
  38289. },
  38290. enumerable: true,
  38291. configurable: true
  38292. });
  38293. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38294. get: function () {
  38295. var keyboard = this.inputs.attached["keyboard"];
  38296. if (keyboard)
  38297. return keyboard.keysRight;
  38298. return [];
  38299. },
  38300. set: function (value) {
  38301. var keyboard = this.inputs.attached["keyboard"];
  38302. if (keyboard)
  38303. keyboard.keysRight = value;
  38304. },
  38305. enumerable: true,
  38306. configurable: true
  38307. });
  38308. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38309. get: function () {
  38310. var mousewheel = this.inputs.attached["mousewheel"];
  38311. if (mousewheel)
  38312. return mousewheel.wheelPrecision;
  38313. return 0;
  38314. },
  38315. set: function (value) {
  38316. var mousewheel = this.inputs.attached["mousewheel"];
  38317. if (mousewheel)
  38318. mousewheel.wheelPrecision = value;
  38319. },
  38320. enumerable: true,
  38321. configurable: true
  38322. });
  38323. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38324. get: function () {
  38325. var mousewheel = this.inputs.attached["mousewheel"];
  38326. if (mousewheel)
  38327. return mousewheel.wheelDeltaPercentage;
  38328. return 0;
  38329. },
  38330. set: function (value) {
  38331. var mousewheel = this.inputs.attached["mousewheel"];
  38332. if (mousewheel)
  38333. mousewheel.wheelDeltaPercentage = value;
  38334. },
  38335. enumerable: true,
  38336. configurable: true
  38337. });
  38338. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38339. get: function () {
  38340. return this._bouncingBehavior;
  38341. },
  38342. enumerable: true,
  38343. configurable: true
  38344. });
  38345. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38346. get: function () {
  38347. return this._bouncingBehavior != null;
  38348. },
  38349. set: function (value) {
  38350. if (value === this.useBouncingBehavior) {
  38351. return;
  38352. }
  38353. if (value) {
  38354. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38355. this.addBehavior(this._bouncingBehavior);
  38356. }
  38357. else if (this._bouncingBehavior) {
  38358. this.removeBehavior(this._bouncingBehavior);
  38359. this._bouncingBehavior = null;
  38360. }
  38361. },
  38362. enumerable: true,
  38363. configurable: true
  38364. });
  38365. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38366. get: function () {
  38367. return this._framingBehavior;
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38373. get: function () {
  38374. return this._framingBehavior != null;
  38375. },
  38376. set: function (value) {
  38377. if (value === this.useFramingBehavior) {
  38378. return;
  38379. }
  38380. if (value) {
  38381. this._framingBehavior = new BABYLON.FramingBehavior();
  38382. this.addBehavior(this._framingBehavior);
  38383. }
  38384. else if (this._framingBehavior) {
  38385. this.removeBehavior(this._framingBehavior);
  38386. this._framingBehavior = null;
  38387. }
  38388. },
  38389. enumerable: true,
  38390. configurable: true
  38391. });
  38392. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38393. get: function () {
  38394. return this._autoRotationBehavior;
  38395. },
  38396. enumerable: true,
  38397. configurable: true
  38398. });
  38399. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38400. get: function () {
  38401. return this._autoRotationBehavior != null;
  38402. },
  38403. set: function (value) {
  38404. if (value === this.useAutoRotationBehavior) {
  38405. return;
  38406. }
  38407. if (value) {
  38408. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38409. this.addBehavior(this._autoRotationBehavior);
  38410. }
  38411. else if (this._autoRotationBehavior) {
  38412. this.removeBehavior(this._autoRotationBehavior);
  38413. this._autoRotationBehavior = null;
  38414. }
  38415. },
  38416. enumerable: true,
  38417. configurable: true
  38418. });
  38419. // Cache
  38420. ArcRotateCamera.prototype._initCache = function () {
  38421. _super.prototype._initCache.call(this);
  38422. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38423. this._cache.alpha = undefined;
  38424. this._cache.beta = undefined;
  38425. this._cache.radius = undefined;
  38426. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38427. };
  38428. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38429. if (!ignoreParentClass) {
  38430. _super.prototype._updateCache.call(this);
  38431. }
  38432. this._cache._target.copyFrom(this._getTargetPosition());
  38433. this._cache.alpha = this.alpha;
  38434. this._cache.beta = this.beta;
  38435. this._cache.radius = this.radius;
  38436. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38437. };
  38438. ArcRotateCamera.prototype._getTargetPosition = function () {
  38439. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38440. var pos = this._targetHost.getAbsolutePosition();
  38441. if (this._targetBoundingCenter) {
  38442. pos.addToRef(this._targetBoundingCenter, this._target);
  38443. }
  38444. else {
  38445. this._target.copyFrom(pos);
  38446. }
  38447. }
  38448. var lockedTargetPosition = this._getLockedTargetPosition();
  38449. if (lockedTargetPosition) {
  38450. return lockedTargetPosition;
  38451. }
  38452. return this._target;
  38453. };
  38454. ArcRotateCamera.prototype.storeState = function () {
  38455. this._storedAlpha = this.alpha;
  38456. this._storedBeta = this.beta;
  38457. this._storedRadius = this.radius;
  38458. this._storedTarget = this._getTargetPosition().clone();
  38459. return _super.prototype.storeState.call(this);
  38460. };
  38461. /**
  38462. * Restored camera state. You must call storeState() first
  38463. */
  38464. ArcRotateCamera.prototype._restoreStateValues = function () {
  38465. if (!_super.prototype._restoreStateValues.call(this)) {
  38466. return false;
  38467. }
  38468. this.alpha = this._storedAlpha;
  38469. this.beta = this._storedBeta;
  38470. this.radius = this._storedRadius;
  38471. this.setTarget(this._storedTarget.clone());
  38472. this.inertialAlphaOffset = 0;
  38473. this.inertialBetaOffset = 0;
  38474. this.inertialRadiusOffset = 0;
  38475. this.inertialPanningX = 0;
  38476. this.inertialPanningY = 0;
  38477. return true;
  38478. };
  38479. // Synchronized
  38480. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38481. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38482. return false;
  38483. return this._cache._target.equals(this._getTargetPosition())
  38484. && this._cache.alpha === this.alpha
  38485. && this._cache.beta === this.beta
  38486. && this._cache.radius === this.radius
  38487. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38488. };
  38489. // Methods
  38490. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38491. var _this = this;
  38492. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38493. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38494. this._useCtrlForPanning = useCtrlForPanning;
  38495. this._panningMouseButton = panningMouseButton;
  38496. this.inputs.attachElement(element, noPreventDefault);
  38497. this._reset = function () {
  38498. _this.inertialAlphaOffset = 0;
  38499. _this.inertialBetaOffset = 0;
  38500. _this.inertialRadiusOffset = 0;
  38501. _this.inertialPanningX = 0;
  38502. _this.inertialPanningY = 0;
  38503. };
  38504. };
  38505. ArcRotateCamera.prototype.detachControl = function (element) {
  38506. this.inputs.detachElement(element);
  38507. if (this._reset) {
  38508. this._reset();
  38509. }
  38510. };
  38511. ArcRotateCamera.prototype._checkInputs = function () {
  38512. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38513. if (this._collisionTriggered) {
  38514. return;
  38515. }
  38516. this.inputs.checkInputs();
  38517. // Inertia
  38518. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38519. if (this.getScene().useRightHandedSystem) {
  38520. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38521. }
  38522. else {
  38523. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38524. }
  38525. this.beta += this.inertialBetaOffset;
  38526. this.radius -= this.inertialRadiusOffset;
  38527. this.inertialAlphaOffset *= this.inertia;
  38528. this.inertialBetaOffset *= this.inertia;
  38529. this.inertialRadiusOffset *= this.inertia;
  38530. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38531. this.inertialAlphaOffset = 0;
  38532. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38533. this.inertialBetaOffset = 0;
  38534. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38535. this.inertialRadiusOffset = 0;
  38536. }
  38537. // Panning inertia
  38538. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38539. if (!this._localDirection) {
  38540. this._localDirection = BABYLON.Vector3.Zero();
  38541. this._transformedDirection = BABYLON.Vector3.Zero();
  38542. }
  38543. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38544. this._localDirection.multiplyInPlace(this.panningAxis);
  38545. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38546. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38547. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38548. if (!this.panningAxis.y) {
  38549. this._transformedDirection.y = 0;
  38550. }
  38551. if (!this._targetHost) {
  38552. if (this.panningDistanceLimit) {
  38553. this._transformedDirection.addInPlace(this._target);
  38554. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38555. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38556. this._target.copyFrom(this._transformedDirection);
  38557. }
  38558. }
  38559. else {
  38560. this._target.addInPlace(this._transformedDirection);
  38561. }
  38562. }
  38563. this.inertialPanningX *= this.panningInertia;
  38564. this.inertialPanningY *= this.panningInertia;
  38565. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38566. this.inertialPanningX = 0;
  38567. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38568. this.inertialPanningY = 0;
  38569. }
  38570. // Limits
  38571. this._checkLimits();
  38572. _super.prototype._checkInputs.call(this);
  38573. };
  38574. ArcRotateCamera.prototype._checkLimits = function () {
  38575. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38576. if (this.allowUpsideDown && this.beta > Math.PI) {
  38577. this.beta = this.beta - (2 * Math.PI);
  38578. }
  38579. }
  38580. else {
  38581. if (this.beta < this.lowerBetaLimit) {
  38582. this.beta = this.lowerBetaLimit;
  38583. }
  38584. }
  38585. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38586. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38587. this.beta = this.beta + (2 * Math.PI);
  38588. }
  38589. }
  38590. else {
  38591. if (this.beta > this.upperBetaLimit) {
  38592. this.beta = this.upperBetaLimit;
  38593. }
  38594. }
  38595. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38596. this.alpha = this.lowerAlphaLimit;
  38597. }
  38598. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38599. this.alpha = this.upperAlphaLimit;
  38600. }
  38601. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38602. this.radius = this.lowerRadiusLimit;
  38603. }
  38604. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38605. this.radius = this.upperRadiusLimit;
  38606. }
  38607. };
  38608. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38609. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38610. this.radius = radiusv3.length();
  38611. if (this.radius === 0) {
  38612. this.radius = 0.0001; // Just to avoid division by zero
  38613. }
  38614. // Alpha
  38615. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38616. if (radiusv3.z < 0) {
  38617. this.alpha = 2 * Math.PI - this.alpha;
  38618. }
  38619. // Beta
  38620. this.beta = Math.acos(radiusv3.y / this.radius);
  38621. this._checkLimits();
  38622. };
  38623. ArcRotateCamera.prototype.setPosition = function (position) {
  38624. if (this.position.equals(position)) {
  38625. return;
  38626. }
  38627. this.position.copyFrom(position);
  38628. this.rebuildAnglesAndRadius();
  38629. };
  38630. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  38631. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  38632. if (allowSamePosition === void 0) { allowSamePosition = false; }
  38633. if (target.getBoundingInfo) {
  38634. if (toBoundingCenter) {
  38635. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  38636. }
  38637. else {
  38638. this._targetBoundingCenter = null;
  38639. }
  38640. this._targetHost = target;
  38641. this._target = this._getTargetPosition();
  38642. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  38643. }
  38644. else {
  38645. var newTarget = target;
  38646. var currentTarget = this._getTargetPosition();
  38647. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  38648. return;
  38649. }
  38650. this._targetHost = null;
  38651. this._target = newTarget;
  38652. this._targetBoundingCenter = null;
  38653. this.onMeshTargetChangedObservable.notifyObservers(null);
  38654. }
  38655. this.rebuildAnglesAndRadius();
  38656. };
  38657. ArcRotateCamera.prototype._getViewMatrix = function () {
  38658. // Compute
  38659. var cosa = Math.cos(this.alpha);
  38660. var sina = Math.sin(this.alpha);
  38661. var cosb = Math.cos(this.beta);
  38662. var sinb = Math.sin(this.beta);
  38663. if (sinb === 0) {
  38664. sinb = 0.0001;
  38665. }
  38666. var target = this._getTargetPosition();
  38667. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  38668. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  38669. if (!this._collider) {
  38670. this._collider = new BABYLON.Collider();
  38671. }
  38672. this._collider.radius = this.collisionRadius;
  38673. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  38674. this._collisionTriggered = true;
  38675. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38676. }
  38677. else {
  38678. this.position.copyFrom(this._newPosition);
  38679. var up = this.upVector;
  38680. if (this.allowUpsideDown && sinb < 0) {
  38681. up = up.clone();
  38682. up = up.negate();
  38683. }
  38684. if (this.getScene().useRightHandedSystem) {
  38685. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  38686. }
  38687. else {
  38688. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  38689. }
  38690. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  38691. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  38692. }
  38693. this._currentTarget = target;
  38694. return this._viewMatrix;
  38695. };
  38696. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  38697. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38698. meshes = meshes || this.getScene().meshes;
  38699. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  38700. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  38701. this.radius = distance * this.zoomOnFactor;
  38702. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  38703. };
  38704. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  38705. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38706. var meshesOrMinMaxVector;
  38707. var distance;
  38708. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  38709. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  38710. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  38711. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  38712. }
  38713. else {
  38714. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  38715. meshesOrMinMaxVector = minMaxVectorAndDistance;
  38716. distance = minMaxVectorAndDistance.distance;
  38717. }
  38718. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  38719. if (!doNotUpdateMaxZ) {
  38720. this.maxZ = distance * 2;
  38721. }
  38722. };
  38723. /**
  38724. * @override
  38725. * Override Camera.createRigCamera
  38726. */
  38727. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38728. var alphaShift = 0;
  38729. switch (this.cameraRigMode) {
  38730. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38731. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38732. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38733. case BABYLON.Camera.RIG_MODE_VR:
  38734. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  38735. break;
  38736. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38737. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  38738. break;
  38739. }
  38740. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  38741. rigCam._cameraRigParams = {};
  38742. return rigCam;
  38743. };
  38744. /**
  38745. * @override
  38746. * Override Camera._updateRigCameras
  38747. */
  38748. ArcRotateCamera.prototype._updateRigCameras = function () {
  38749. var camLeft = this._rigCameras[0];
  38750. var camRight = this._rigCameras[1];
  38751. camLeft.beta = camRight.beta = this.beta;
  38752. camLeft.radius = camRight.radius = this.radius;
  38753. switch (this.cameraRigMode) {
  38754. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38755. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38756. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38757. case BABYLON.Camera.RIG_MODE_VR:
  38758. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38759. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38760. break;
  38761. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38762. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38763. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38764. break;
  38765. }
  38766. _super.prototype._updateRigCameras.call(this);
  38767. };
  38768. ArcRotateCamera.prototype.dispose = function () {
  38769. this.inputs.clear();
  38770. _super.prototype.dispose.call(this);
  38771. };
  38772. ArcRotateCamera.prototype.getClassName = function () {
  38773. return "ArcRotateCamera";
  38774. };
  38775. __decorate([
  38776. BABYLON.serialize()
  38777. ], ArcRotateCamera.prototype, "alpha", void 0);
  38778. __decorate([
  38779. BABYLON.serialize()
  38780. ], ArcRotateCamera.prototype, "beta", void 0);
  38781. __decorate([
  38782. BABYLON.serialize()
  38783. ], ArcRotateCamera.prototype, "radius", void 0);
  38784. __decorate([
  38785. BABYLON.serializeAsVector3("target")
  38786. ], ArcRotateCamera.prototype, "_target", void 0);
  38787. __decorate([
  38788. BABYLON.serialize()
  38789. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  38790. __decorate([
  38791. BABYLON.serialize()
  38792. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  38793. __decorate([
  38794. BABYLON.serialize()
  38795. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  38796. __decorate([
  38797. BABYLON.serialize()
  38798. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  38799. __decorate([
  38800. BABYLON.serialize()
  38801. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  38802. __decorate([
  38803. BABYLON.serialize()
  38804. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  38805. __decorate([
  38806. BABYLON.serialize()
  38807. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  38808. __decorate([
  38809. BABYLON.serialize()
  38810. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  38811. __decorate([
  38812. BABYLON.serialize()
  38813. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  38814. __decorate([
  38815. BABYLON.serialize()
  38816. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  38817. __decorate([
  38818. BABYLON.serialize()
  38819. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  38820. __decorate([
  38821. BABYLON.serialize()
  38822. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  38823. __decorate([
  38824. BABYLON.serialize()
  38825. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  38826. __decorate([
  38827. BABYLON.serializeAsVector3()
  38828. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  38829. __decorate([
  38830. BABYLON.serialize()
  38831. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  38832. __decorate([
  38833. BABYLON.serialize()
  38834. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  38835. __decorate([
  38836. BABYLON.serialize()
  38837. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  38838. return ArcRotateCamera;
  38839. }(BABYLON.TargetCamera));
  38840. BABYLON.ArcRotateCamera = ArcRotateCamera;
  38841. })(BABYLON || (BABYLON = {}));
  38842. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  38843. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  38844. var BABYLON;
  38845. (function (BABYLON) {
  38846. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  38847. __extends(ArcRotateCameraInputsManager, _super);
  38848. function ArcRotateCameraInputsManager(camera) {
  38849. return _super.call(this, camera) || this;
  38850. }
  38851. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  38852. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  38853. return this;
  38854. };
  38855. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  38856. this.add(new BABYLON.ArcRotateCameraPointersInput());
  38857. return this;
  38858. };
  38859. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  38860. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  38861. return this;
  38862. };
  38863. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  38864. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  38865. return this;
  38866. };
  38867. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  38868. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  38869. return this;
  38870. };
  38871. return ArcRotateCameraInputsManager;
  38872. }(BABYLON.CameraInputsManager));
  38873. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  38874. })(BABYLON || (BABYLON = {}));
  38875. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  38876. var BABYLON;
  38877. (function (BABYLON) {
  38878. var HemisphericLight = /** @class */ (function (_super) {
  38879. __extends(HemisphericLight, _super);
  38880. /**
  38881. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  38882. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  38883. * The HemisphericLight can't cast shadows.
  38884. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38885. */
  38886. function HemisphericLight(name, direction, scene) {
  38887. var _this = _super.call(this, name, scene) || this;
  38888. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  38889. _this.direction = direction || BABYLON.Vector3.Up();
  38890. return _this;
  38891. }
  38892. HemisphericLight.prototype._buildUniformLayout = function () {
  38893. this._uniformBuffer.addUniform("vLightData", 4);
  38894. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38895. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38896. this._uniformBuffer.addUniform("vLightGround", 3);
  38897. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38898. this._uniformBuffer.addUniform("depthValues", 2);
  38899. this._uniformBuffer.create();
  38900. };
  38901. /**
  38902. * Returns the string "HemisphericLight".
  38903. */
  38904. HemisphericLight.prototype.getClassName = function () {
  38905. return "HemisphericLight";
  38906. };
  38907. /**
  38908. * Sets the HemisphericLight direction towards the passed target (Vector3).
  38909. * Returns the updated direction.
  38910. */
  38911. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  38912. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  38913. return this.direction;
  38914. };
  38915. HemisphericLight.prototype.getShadowGenerator = function () {
  38916. return null;
  38917. };
  38918. /**
  38919. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  38920. * Returns the HemisphericLight.
  38921. */
  38922. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  38923. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  38924. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  38925. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  38926. return this;
  38927. };
  38928. HemisphericLight.prototype._getWorldMatrix = function () {
  38929. if (!this._worldMatrix) {
  38930. this._worldMatrix = BABYLON.Matrix.Identity();
  38931. }
  38932. return this._worldMatrix;
  38933. };
  38934. /**
  38935. * Returns the integer 3.
  38936. */
  38937. HemisphericLight.prototype.getTypeID = function () {
  38938. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  38939. };
  38940. __decorate([
  38941. BABYLON.serializeAsColor3()
  38942. ], HemisphericLight.prototype, "groundColor", void 0);
  38943. __decorate([
  38944. BABYLON.serializeAsVector3()
  38945. ], HemisphericLight.prototype, "direction", void 0);
  38946. return HemisphericLight;
  38947. }(BABYLON.Light));
  38948. BABYLON.HemisphericLight = HemisphericLight;
  38949. })(BABYLON || (BABYLON = {}));
  38950. //# sourceMappingURL=babylon.hemisphericLight.js.map
  38951. var BABYLON;
  38952. (function (BABYLON) {
  38953. var ShadowLight = /** @class */ (function (_super) {
  38954. __extends(ShadowLight, _super);
  38955. function ShadowLight() {
  38956. var _this = _super !== null && _super.apply(this, arguments) || this;
  38957. _this._needProjectionMatrixCompute = true;
  38958. return _this;
  38959. }
  38960. Object.defineProperty(ShadowLight.prototype, "direction", {
  38961. get: function () {
  38962. return this._direction;
  38963. },
  38964. set: function (value) {
  38965. this._direction = value;
  38966. },
  38967. enumerable: true,
  38968. configurable: true
  38969. });
  38970. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  38971. get: function () {
  38972. return this._shadowMinZ;
  38973. },
  38974. set: function (value) {
  38975. this._shadowMinZ = value;
  38976. this.forceProjectionMatrixCompute();
  38977. },
  38978. enumerable: true,
  38979. configurable: true
  38980. });
  38981. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  38982. get: function () {
  38983. return this._shadowMaxZ;
  38984. },
  38985. set: function (value) {
  38986. this._shadowMaxZ = value;
  38987. this.forceProjectionMatrixCompute();
  38988. },
  38989. enumerable: true,
  38990. configurable: true
  38991. });
  38992. /**
  38993. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  38994. */
  38995. ShadowLight.prototype.computeTransformedInformation = function () {
  38996. if (this.parent && this.parent.getWorldMatrix) {
  38997. if (!this.transformedPosition) {
  38998. this.transformedPosition = BABYLON.Vector3.Zero();
  38999. }
  39000. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39001. // In case the direction is present.
  39002. if (this.direction) {
  39003. if (!this.transformedDirection) {
  39004. this.transformedDirection = BABYLON.Vector3.Zero();
  39005. }
  39006. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39007. }
  39008. return true;
  39009. }
  39010. return false;
  39011. };
  39012. /**
  39013. * Return the depth scale used for the shadow map.
  39014. */
  39015. ShadowLight.prototype.getDepthScale = function () {
  39016. return 50.0;
  39017. };
  39018. /**
  39019. * Returns the light direction (Vector3) for any passed face index.
  39020. */
  39021. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39022. return this.transformedDirection ? this.transformedDirection : this.direction;
  39023. };
  39024. /**
  39025. * Returns the DirectionalLight absolute position in the World.
  39026. */
  39027. ShadowLight.prototype.getAbsolutePosition = function () {
  39028. return this.transformedPosition ? this.transformedPosition : this.position;
  39029. };
  39030. /**
  39031. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39032. * Returns the updated DirectionalLight direction (Vector3).
  39033. */
  39034. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39035. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39036. return this.direction;
  39037. };
  39038. /**
  39039. * Returns the light rotation (Vector3).
  39040. */
  39041. ShadowLight.prototype.getRotation = function () {
  39042. this.direction.normalize();
  39043. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39044. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39045. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39046. };
  39047. /**
  39048. * Boolean : false by default.
  39049. */
  39050. ShadowLight.prototype.needCube = function () {
  39051. return false;
  39052. };
  39053. /**
  39054. * Specifies wether or not the projection matrix should be recomputed this frame.
  39055. */
  39056. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39057. return this._needProjectionMatrixCompute;
  39058. };
  39059. /**
  39060. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39061. */
  39062. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39063. this._needProjectionMatrixCompute = true;
  39064. };
  39065. /**
  39066. * Get the world matrix of the sahdow lights.
  39067. */
  39068. ShadowLight.prototype._getWorldMatrix = function () {
  39069. if (!this._worldMatrix) {
  39070. this._worldMatrix = BABYLON.Matrix.Identity();
  39071. }
  39072. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39073. return this._worldMatrix;
  39074. };
  39075. /**
  39076. * Gets the minZ used for shadow according to both the scene and the light.
  39077. * @param activeCamera
  39078. */
  39079. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39080. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39081. };
  39082. /**
  39083. * Gets the maxZ used for shadow according to both the scene and the light.
  39084. * @param activeCamera
  39085. */
  39086. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39087. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39088. };
  39089. /**
  39090. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39091. * Returns the light.
  39092. */
  39093. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39094. if (this.customProjectionMatrixBuilder) {
  39095. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39096. }
  39097. else {
  39098. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39099. }
  39100. return this;
  39101. };
  39102. __decorate([
  39103. BABYLON.serializeAsVector3()
  39104. ], ShadowLight.prototype, "position", void 0);
  39105. __decorate([
  39106. BABYLON.serializeAsVector3()
  39107. ], ShadowLight.prototype, "direction", null);
  39108. __decorate([
  39109. BABYLON.serialize()
  39110. ], ShadowLight.prototype, "shadowMinZ", null);
  39111. __decorate([
  39112. BABYLON.serialize()
  39113. ], ShadowLight.prototype, "shadowMaxZ", null);
  39114. return ShadowLight;
  39115. }(BABYLON.Light));
  39116. BABYLON.ShadowLight = ShadowLight;
  39117. })(BABYLON || (BABYLON = {}));
  39118. //# sourceMappingURL=babylon.shadowLight.js.map
  39119. var BABYLON;
  39120. (function (BABYLON) {
  39121. var PointLight = /** @class */ (function (_super) {
  39122. __extends(PointLight, _super);
  39123. /**
  39124. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39125. * A PointLight emits the light in every direction.
  39126. * It can cast shadows.
  39127. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39128. * ```javascript
  39129. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39130. * ```
  39131. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39132. */
  39133. function PointLight(name, position, scene) {
  39134. var _this = _super.call(this, name, scene) || this;
  39135. _this._shadowAngle = Math.PI / 2;
  39136. _this.position = position;
  39137. return _this;
  39138. }
  39139. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39140. /**
  39141. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39142. * This specifies what angle the shadow will use to be created.
  39143. *
  39144. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39145. */
  39146. get: function () {
  39147. return this._shadowAngle;
  39148. },
  39149. /**
  39150. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39151. * This specifies what angle the shadow will use to be created.
  39152. *
  39153. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39154. */
  39155. set: function (value) {
  39156. this._shadowAngle = value;
  39157. this.forceProjectionMatrixCompute();
  39158. },
  39159. enumerable: true,
  39160. configurable: true
  39161. });
  39162. Object.defineProperty(PointLight.prototype, "direction", {
  39163. get: function () {
  39164. return this._direction;
  39165. },
  39166. /**
  39167. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39168. */
  39169. set: function (value) {
  39170. var previousNeedCube = this.needCube();
  39171. this._direction = value;
  39172. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39173. this._shadowGenerator.recreateShadowMap();
  39174. }
  39175. },
  39176. enumerable: true,
  39177. configurable: true
  39178. });
  39179. /**
  39180. * Returns the string "PointLight"
  39181. */
  39182. PointLight.prototype.getClassName = function () {
  39183. return "PointLight";
  39184. };
  39185. /**
  39186. * Returns the integer 0.
  39187. */
  39188. PointLight.prototype.getTypeID = function () {
  39189. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39190. };
  39191. /**
  39192. * Specifies wether or not the shadowmap should be a cube texture.
  39193. */
  39194. PointLight.prototype.needCube = function () {
  39195. return !this.direction;
  39196. };
  39197. /**
  39198. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39199. */
  39200. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39201. if (this.direction) {
  39202. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39203. }
  39204. else {
  39205. switch (faceIndex) {
  39206. case 0:
  39207. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39208. case 1:
  39209. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39210. case 2:
  39211. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39212. case 3:
  39213. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39214. case 4:
  39215. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39216. case 5:
  39217. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39218. }
  39219. }
  39220. return BABYLON.Vector3.Zero();
  39221. };
  39222. /**
  39223. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39224. * - fov = PI / 2
  39225. * - aspect ratio : 1.0
  39226. * - z-near and far equal to the active camera minZ and maxZ.
  39227. * Returns the PointLight.
  39228. */
  39229. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39230. var activeCamera = this.getScene().activeCamera;
  39231. if (!activeCamera) {
  39232. return;
  39233. }
  39234. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39235. };
  39236. PointLight.prototype._buildUniformLayout = function () {
  39237. this._uniformBuffer.addUniform("vLightData", 4);
  39238. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39239. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39240. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39241. this._uniformBuffer.addUniform("depthValues", 2);
  39242. this._uniformBuffer.create();
  39243. };
  39244. /**
  39245. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39246. * Returns the PointLight.
  39247. */
  39248. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39249. if (this.computeTransformedInformation()) {
  39250. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39251. return this;
  39252. }
  39253. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39254. return this;
  39255. };
  39256. __decorate([
  39257. BABYLON.serialize()
  39258. ], PointLight.prototype, "shadowAngle", null);
  39259. return PointLight;
  39260. }(BABYLON.ShadowLight));
  39261. BABYLON.PointLight = PointLight;
  39262. })(BABYLON || (BABYLON = {}));
  39263. //# sourceMappingURL=babylon.pointLight.js.map
  39264. /// <reference path="babylon.light.ts" />
  39265. var BABYLON;
  39266. (function (BABYLON) {
  39267. var DirectionalLight = /** @class */ (function (_super) {
  39268. __extends(DirectionalLight, _super);
  39269. /**
  39270. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39271. * The directional light is emitted from everywhere in the given direction.
  39272. * It can cast shawdows.
  39273. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39274. */
  39275. function DirectionalLight(name, direction, scene) {
  39276. var _this = _super.call(this, name, scene) || this;
  39277. _this._shadowFrustumSize = 0;
  39278. _this._shadowOrthoScale = 0.5;
  39279. _this.autoUpdateExtends = true;
  39280. // Cache
  39281. _this._orthoLeft = Number.MAX_VALUE;
  39282. _this._orthoRight = Number.MIN_VALUE;
  39283. _this._orthoTop = Number.MIN_VALUE;
  39284. _this._orthoBottom = Number.MAX_VALUE;
  39285. _this.position = direction.scale(-1.0);
  39286. _this.direction = direction;
  39287. return _this;
  39288. }
  39289. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39290. /**
  39291. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39292. */
  39293. get: function () {
  39294. return this._shadowFrustumSize;
  39295. },
  39296. /**
  39297. * Specifies a fix frustum size for the shadow generation.
  39298. */
  39299. set: function (value) {
  39300. this._shadowFrustumSize = value;
  39301. this.forceProjectionMatrixCompute();
  39302. },
  39303. enumerable: true,
  39304. configurable: true
  39305. });
  39306. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39307. get: function () {
  39308. return this._shadowOrthoScale;
  39309. },
  39310. set: function (value) {
  39311. this._shadowOrthoScale = value;
  39312. this.forceProjectionMatrixCompute();
  39313. },
  39314. enumerable: true,
  39315. configurable: true
  39316. });
  39317. /**
  39318. * Returns the string "DirectionalLight".
  39319. */
  39320. DirectionalLight.prototype.getClassName = function () {
  39321. return "DirectionalLight";
  39322. };
  39323. /**
  39324. * Returns the integer 1.
  39325. */
  39326. DirectionalLight.prototype.getTypeID = function () {
  39327. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39328. };
  39329. /**
  39330. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39331. * Returns the DirectionalLight Shadow projection matrix.
  39332. */
  39333. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39334. if (this.shadowFrustumSize > 0) {
  39335. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39336. }
  39337. else {
  39338. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39339. }
  39340. };
  39341. /**
  39342. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39343. * Returns the DirectionalLight Shadow projection matrix.
  39344. */
  39345. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39346. var activeCamera = this.getScene().activeCamera;
  39347. if (!activeCamera) {
  39348. return;
  39349. }
  39350. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39351. };
  39352. /**
  39353. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39354. * Returns the DirectionalLight Shadow projection matrix.
  39355. */
  39356. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39357. var activeCamera = this.getScene().activeCamera;
  39358. if (!activeCamera) {
  39359. return;
  39360. }
  39361. // Check extends
  39362. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39363. var tempVector3 = BABYLON.Vector3.Zero();
  39364. this._orthoLeft = Number.MAX_VALUE;
  39365. this._orthoRight = Number.MIN_VALUE;
  39366. this._orthoTop = Number.MIN_VALUE;
  39367. this._orthoBottom = Number.MAX_VALUE;
  39368. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39369. var mesh = renderList[meshIndex];
  39370. if (!mesh) {
  39371. continue;
  39372. }
  39373. var boundingInfo = mesh.getBoundingInfo();
  39374. if (!boundingInfo) {
  39375. continue;
  39376. }
  39377. var boundingBox = boundingInfo.boundingBox;
  39378. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39379. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39380. if (tempVector3.x < this._orthoLeft)
  39381. this._orthoLeft = tempVector3.x;
  39382. if (tempVector3.y < this._orthoBottom)
  39383. this._orthoBottom = tempVector3.y;
  39384. if (tempVector3.x > this._orthoRight)
  39385. this._orthoRight = tempVector3.x;
  39386. if (tempVector3.y > this._orthoTop)
  39387. this._orthoTop = tempVector3.y;
  39388. }
  39389. }
  39390. }
  39391. var xOffset = this._orthoRight - this._orthoLeft;
  39392. var yOffset = this._orthoTop - this._orthoBottom;
  39393. 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);
  39394. };
  39395. DirectionalLight.prototype._buildUniformLayout = function () {
  39396. this._uniformBuffer.addUniform("vLightData", 4);
  39397. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39398. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39399. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39400. this._uniformBuffer.addUniform("depthValues", 2);
  39401. this._uniformBuffer.create();
  39402. };
  39403. /**
  39404. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39405. * Returns the DirectionalLight.
  39406. */
  39407. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39408. if (this.computeTransformedInformation()) {
  39409. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39410. return this;
  39411. }
  39412. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39413. return this;
  39414. };
  39415. /**
  39416. * Gets the minZ used for shadow according to both the scene and the light.
  39417. *
  39418. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39419. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39420. * @param activeCamera
  39421. */
  39422. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39423. return 1;
  39424. };
  39425. /**
  39426. * Gets the maxZ used for shadow according to both the scene and the light.
  39427. *
  39428. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39429. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39430. * @param activeCamera
  39431. */
  39432. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39433. return 1;
  39434. };
  39435. __decorate([
  39436. BABYLON.serialize()
  39437. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39438. __decorate([
  39439. BABYLON.serialize()
  39440. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39441. __decorate([
  39442. BABYLON.serialize()
  39443. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39444. return DirectionalLight;
  39445. }(BABYLON.ShadowLight));
  39446. BABYLON.DirectionalLight = DirectionalLight;
  39447. })(BABYLON || (BABYLON = {}));
  39448. //# sourceMappingURL=babylon.directionalLight.js.map
  39449. var BABYLON;
  39450. (function (BABYLON) {
  39451. var SpotLight = /** @class */ (function (_super) {
  39452. __extends(SpotLight, _super);
  39453. /**
  39454. * Creates a SpotLight object in the scene with the passed parameters :
  39455. * - `position` (Vector3) is the initial SpotLight position,
  39456. * - `direction` (Vector3) is the initial SpotLight direction,
  39457. * - `angle` (float, in radians) is the spot light cone angle,
  39458. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39459. * A spot light is a simply light oriented cone.
  39460. * It can cast shadows.
  39461. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39462. */
  39463. function SpotLight(name, position, direction, angle, exponent, scene) {
  39464. var _this = _super.call(this, name, scene) || this;
  39465. _this.position = position;
  39466. _this.direction = direction;
  39467. _this.angle = angle;
  39468. _this.exponent = exponent;
  39469. return _this;
  39470. }
  39471. Object.defineProperty(SpotLight.prototype, "angle", {
  39472. get: function () {
  39473. return this._angle;
  39474. },
  39475. set: function (value) {
  39476. this._angle = value;
  39477. this.forceProjectionMatrixCompute();
  39478. },
  39479. enumerable: true,
  39480. configurable: true
  39481. });
  39482. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39483. get: function () {
  39484. return this._shadowAngleScale;
  39485. },
  39486. /**
  39487. * Allows scaling the angle of the light for shadow generation only.
  39488. */
  39489. set: function (value) {
  39490. this._shadowAngleScale = value;
  39491. this.forceProjectionMatrixCompute();
  39492. },
  39493. enumerable: true,
  39494. configurable: true
  39495. });
  39496. /**
  39497. * Returns the string "SpotLight".
  39498. */
  39499. SpotLight.prototype.getClassName = function () {
  39500. return "SpotLight";
  39501. };
  39502. /**
  39503. * Returns the integer 2.
  39504. */
  39505. SpotLight.prototype.getTypeID = function () {
  39506. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39507. };
  39508. /**
  39509. * 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.
  39510. * Returns the SpotLight.
  39511. */
  39512. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39513. var activeCamera = this.getScene().activeCamera;
  39514. if (!activeCamera) {
  39515. return;
  39516. }
  39517. this._shadowAngleScale = this._shadowAngleScale || 1;
  39518. var angle = this._shadowAngleScale * this._angle;
  39519. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39520. };
  39521. SpotLight.prototype._buildUniformLayout = function () {
  39522. this._uniformBuffer.addUniform("vLightData", 4);
  39523. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39524. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39525. this._uniformBuffer.addUniform("vLightDirection", 3);
  39526. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39527. this._uniformBuffer.addUniform("depthValues", 2);
  39528. this._uniformBuffer.create();
  39529. };
  39530. /**
  39531. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39532. * Return the SpotLight.
  39533. */
  39534. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39535. var normalizeDirection;
  39536. if (this.computeTransformedInformation()) {
  39537. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39538. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39539. }
  39540. else {
  39541. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39542. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39543. }
  39544. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39545. return this;
  39546. };
  39547. __decorate([
  39548. BABYLON.serialize()
  39549. ], SpotLight.prototype, "angle", null);
  39550. __decorate([
  39551. BABYLON.serialize()
  39552. /**
  39553. * Allows scaling the angle of the light for shadow generation only.
  39554. */
  39555. ], SpotLight.prototype, "shadowAngleScale", null);
  39556. __decorate([
  39557. BABYLON.serialize()
  39558. ], SpotLight.prototype, "exponent", void 0);
  39559. return SpotLight;
  39560. }(BABYLON.ShadowLight));
  39561. BABYLON.SpotLight = SpotLight;
  39562. })(BABYLON || (BABYLON = {}));
  39563. //# sourceMappingURL=babylon.spotLight.js.map
  39564. var BABYLON;
  39565. (function (BABYLON) {
  39566. var AnimationRange = /** @class */ (function () {
  39567. function AnimationRange(name, from, to) {
  39568. this.name = name;
  39569. this.from = from;
  39570. this.to = to;
  39571. }
  39572. AnimationRange.prototype.clone = function () {
  39573. return new AnimationRange(this.name, this.from, this.to);
  39574. };
  39575. return AnimationRange;
  39576. }());
  39577. BABYLON.AnimationRange = AnimationRange;
  39578. /**
  39579. * Composed of a frame, and an action function
  39580. */
  39581. var AnimationEvent = /** @class */ (function () {
  39582. function AnimationEvent(frame, action, onlyOnce) {
  39583. this.frame = frame;
  39584. this.action = action;
  39585. this.onlyOnce = onlyOnce;
  39586. this.isDone = false;
  39587. }
  39588. return AnimationEvent;
  39589. }());
  39590. BABYLON.AnimationEvent = AnimationEvent;
  39591. var PathCursor = /** @class */ (function () {
  39592. function PathCursor(path) {
  39593. this.path = path;
  39594. this._onchange = new Array();
  39595. this.value = 0;
  39596. this.animations = new Array();
  39597. }
  39598. PathCursor.prototype.getPoint = function () {
  39599. var point = this.path.getPointAtLengthPosition(this.value);
  39600. return new BABYLON.Vector3(point.x, 0, point.y);
  39601. };
  39602. PathCursor.prototype.moveAhead = function (step) {
  39603. if (step === void 0) { step = 0.002; }
  39604. this.move(step);
  39605. return this;
  39606. };
  39607. PathCursor.prototype.moveBack = function (step) {
  39608. if (step === void 0) { step = 0.002; }
  39609. this.move(-step);
  39610. return this;
  39611. };
  39612. PathCursor.prototype.move = function (step) {
  39613. if (Math.abs(step) > 1) {
  39614. throw "step size should be less than 1.";
  39615. }
  39616. this.value += step;
  39617. this.ensureLimits();
  39618. this.raiseOnChange();
  39619. return this;
  39620. };
  39621. PathCursor.prototype.ensureLimits = function () {
  39622. while (this.value > 1) {
  39623. this.value -= 1;
  39624. }
  39625. while (this.value < 0) {
  39626. this.value += 1;
  39627. }
  39628. return this;
  39629. };
  39630. // used by animation engine
  39631. PathCursor.prototype.raiseOnChange = function () {
  39632. var _this = this;
  39633. this._onchange.forEach(function (f) { return f(_this); });
  39634. return this;
  39635. };
  39636. PathCursor.prototype.onchange = function (f) {
  39637. this._onchange.push(f);
  39638. return this;
  39639. };
  39640. return PathCursor;
  39641. }());
  39642. BABYLON.PathCursor = PathCursor;
  39643. var Animation = /** @class */ (function () {
  39644. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  39645. this.name = name;
  39646. this.targetProperty = targetProperty;
  39647. this.framePerSecond = framePerSecond;
  39648. this.dataType = dataType;
  39649. this.loopMode = loopMode;
  39650. this.enableBlending = enableBlending;
  39651. this._runtimeAnimations = new Array();
  39652. // The set of event that will be linked to this animation
  39653. this._events = new Array();
  39654. this.blendingSpeed = 0.01;
  39655. this._ranges = {};
  39656. this.targetPropertyPath = targetProperty.split(".");
  39657. this.dataType = dataType;
  39658. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  39659. }
  39660. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  39661. var dataType = undefined;
  39662. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  39663. dataType = Animation.ANIMATIONTYPE_FLOAT;
  39664. }
  39665. else if (from instanceof BABYLON.Quaternion) {
  39666. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  39667. }
  39668. else if (from instanceof BABYLON.Vector3) {
  39669. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  39670. }
  39671. else if (from instanceof BABYLON.Vector2) {
  39672. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  39673. }
  39674. else if (from instanceof BABYLON.Color3) {
  39675. dataType = Animation.ANIMATIONTYPE_COLOR3;
  39676. }
  39677. else if (from instanceof BABYLON.Size) {
  39678. dataType = Animation.ANIMATIONTYPE_SIZE;
  39679. }
  39680. if (dataType == undefined) {
  39681. return null;
  39682. }
  39683. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  39684. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  39685. animation.setKeys(keys);
  39686. if (easingFunction !== undefined) {
  39687. animation.setEasingFunction(easingFunction);
  39688. }
  39689. return animation;
  39690. };
  39691. /**
  39692. * Sets up an animation.
  39693. * @param property the property to animate
  39694. * @param animationType the animation type to apply
  39695. * @param easingFunction the easing function used in the animation
  39696. * @returns The created animation
  39697. */
  39698. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  39699. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39700. animation.setEasingFunction(easingFunction);
  39701. return animation;
  39702. };
  39703. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39704. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39705. if (!animation) {
  39706. return null;
  39707. }
  39708. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39709. };
  39710. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39711. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39712. if (!animation) {
  39713. return null;
  39714. }
  39715. node.animations.push(animation);
  39716. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39717. };
  39718. /**
  39719. * Transition property of the Camera to the target Value.
  39720. * @param property The property to transition
  39721. * @param targetValue The target Value of the property
  39722. * @param host The object where the property to animate belongs
  39723. * @param scene Scene used to run the animation
  39724. * @param frameRate Framerate (in frame/s) to use
  39725. * @param transition The transition type we want to use
  39726. * @param duration The duration of the animation, in milliseconds
  39727. * @param onAnimationEnd Call back trigger at the end of the animation.
  39728. */
  39729. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  39730. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  39731. if (duration <= 0) {
  39732. host[property] = targetValue;
  39733. if (onAnimationEnd) {
  39734. onAnimationEnd();
  39735. }
  39736. return null;
  39737. }
  39738. var endFrame = frameRate * (duration / 1000);
  39739. transition.setKeys([{
  39740. frame: 0,
  39741. value: host[property].clone ? host[property].clone() : host[property]
  39742. },
  39743. {
  39744. frame: endFrame,
  39745. value: targetValue
  39746. }]);
  39747. if (!host.animations) {
  39748. host.animations = [];
  39749. }
  39750. host.animations.push(transition);
  39751. var animation = scene.beginAnimation(host, 0, endFrame, false);
  39752. animation.onAnimationEnd = onAnimationEnd;
  39753. return animation;
  39754. };
  39755. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  39756. /**
  39757. * Return the array of runtime animations currently using this animation
  39758. */
  39759. get: function () {
  39760. return this._runtimeAnimations;
  39761. },
  39762. enumerable: true,
  39763. configurable: true
  39764. });
  39765. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  39766. get: function () {
  39767. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  39768. var runtimeAnimation = _a[_i];
  39769. if (!runtimeAnimation.isStopped) {
  39770. return true;
  39771. }
  39772. }
  39773. return false;
  39774. },
  39775. enumerable: true,
  39776. configurable: true
  39777. });
  39778. // Methods
  39779. /**
  39780. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  39781. */
  39782. Animation.prototype.toString = function (fullDetails) {
  39783. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  39784. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  39785. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  39786. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  39787. if (fullDetails) {
  39788. ret += ", Ranges: {";
  39789. var first = true;
  39790. for (var name in this._ranges) {
  39791. if (first) {
  39792. ret += ", ";
  39793. first = false;
  39794. }
  39795. ret += name;
  39796. }
  39797. ret += "}";
  39798. }
  39799. return ret;
  39800. };
  39801. /**
  39802. * Add an event to this animation.
  39803. */
  39804. Animation.prototype.addEvent = function (event) {
  39805. this._events.push(event);
  39806. };
  39807. /**
  39808. * Remove all events found at the given frame
  39809. * @param frame
  39810. */
  39811. Animation.prototype.removeEvents = function (frame) {
  39812. for (var index = 0; index < this._events.length; index++) {
  39813. if (this._events[index].frame === frame) {
  39814. this._events.splice(index, 1);
  39815. index--;
  39816. }
  39817. }
  39818. };
  39819. Animation.prototype.getEvents = function () {
  39820. return this._events;
  39821. };
  39822. Animation.prototype.createRange = function (name, from, to) {
  39823. // check name not already in use; could happen for bones after serialized
  39824. if (!this._ranges[name]) {
  39825. this._ranges[name] = new AnimationRange(name, from, to);
  39826. }
  39827. };
  39828. Animation.prototype.deleteRange = function (name, deleteFrames) {
  39829. if (deleteFrames === void 0) { deleteFrames = true; }
  39830. var range = this._ranges[name];
  39831. if (!range) {
  39832. return;
  39833. }
  39834. if (deleteFrames) {
  39835. var from = range.from;
  39836. var to = range.to;
  39837. // this loop MUST go high to low for multiple splices to work
  39838. for (var key = this._keys.length - 1; key >= 0; key--) {
  39839. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  39840. this._keys.splice(key, 1);
  39841. }
  39842. }
  39843. }
  39844. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  39845. };
  39846. Animation.prototype.getRange = function (name) {
  39847. return this._ranges[name];
  39848. };
  39849. Animation.prototype.getKeys = function () {
  39850. return this._keys;
  39851. };
  39852. Animation.prototype.getHighestFrame = function () {
  39853. var ret = 0;
  39854. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  39855. if (ret < this._keys[key].frame) {
  39856. ret = this._keys[key].frame;
  39857. }
  39858. }
  39859. return ret;
  39860. };
  39861. Animation.prototype.getEasingFunction = function () {
  39862. return this._easingFunction;
  39863. };
  39864. Animation.prototype.setEasingFunction = function (easingFunction) {
  39865. this._easingFunction = easingFunction;
  39866. };
  39867. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  39868. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  39869. };
  39870. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39871. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  39872. };
  39873. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  39874. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  39875. };
  39876. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39877. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  39878. };
  39879. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  39880. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  39881. };
  39882. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39883. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  39884. };
  39885. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  39886. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  39887. };
  39888. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39889. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  39890. };
  39891. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  39892. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  39893. };
  39894. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  39895. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  39896. };
  39897. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  39898. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  39899. };
  39900. Animation.prototype.clone = function () {
  39901. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  39902. clone.enableBlending = this.enableBlending;
  39903. clone.blendingSpeed = this.blendingSpeed;
  39904. if (this._keys) {
  39905. clone.setKeys(this._keys);
  39906. }
  39907. if (this._ranges) {
  39908. clone._ranges = {};
  39909. for (var name in this._ranges) {
  39910. var range = this._ranges[name];
  39911. if (!range) {
  39912. continue;
  39913. }
  39914. clone._ranges[name] = range.clone();
  39915. }
  39916. }
  39917. return clone;
  39918. };
  39919. Animation.prototype.setKeys = function (values) {
  39920. this._keys = values.slice(0);
  39921. };
  39922. Animation.prototype.serialize = function () {
  39923. var serializationObject = {};
  39924. serializationObject.name = this.name;
  39925. serializationObject.property = this.targetProperty;
  39926. serializationObject.framePerSecond = this.framePerSecond;
  39927. serializationObject.dataType = this.dataType;
  39928. serializationObject.loopBehavior = this.loopMode;
  39929. serializationObject.enableBlending = this.enableBlending;
  39930. serializationObject.blendingSpeed = this.blendingSpeed;
  39931. var dataType = this.dataType;
  39932. serializationObject.keys = [];
  39933. var keys = this.getKeys();
  39934. for (var index = 0; index < keys.length; index++) {
  39935. var animationKey = keys[index];
  39936. var key = {};
  39937. key.frame = animationKey.frame;
  39938. switch (dataType) {
  39939. case Animation.ANIMATIONTYPE_FLOAT:
  39940. key.values = [animationKey.value];
  39941. break;
  39942. case Animation.ANIMATIONTYPE_QUATERNION:
  39943. case Animation.ANIMATIONTYPE_MATRIX:
  39944. case Animation.ANIMATIONTYPE_VECTOR3:
  39945. case Animation.ANIMATIONTYPE_COLOR3:
  39946. key.values = animationKey.value.asArray();
  39947. break;
  39948. }
  39949. serializationObject.keys.push(key);
  39950. }
  39951. serializationObject.ranges = [];
  39952. for (var name in this._ranges) {
  39953. var source = this._ranges[name];
  39954. if (!source) {
  39955. continue;
  39956. }
  39957. var range = {};
  39958. range.name = name;
  39959. range.from = source.from;
  39960. range.to = source.to;
  39961. serializationObject.ranges.push(range);
  39962. }
  39963. return serializationObject;
  39964. };
  39965. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  39966. get: function () {
  39967. return Animation._ANIMATIONTYPE_FLOAT;
  39968. },
  39969. enumerable: true,
  39970. configurable: true
  39971. });
  39972. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  39973. get: function () {
  39974. return Animation._ANIMATIONTYPE_VECTOR3;
  39975. },
  39976. enumerable: true,
  39977. configurable: true
  39978. });
  39979. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  39980. get: function () {
  39981. return Animation._ANIMATIONTYPE_VECTOR2;
  39982. },
  39983. enumerable: true,
  39984. configurable: true
  39985. });
  39986. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  39987. get: function () {
  39988. return Animation._ANIMATIONTYPE_SIZE;
  39989. },
  39990. enumerable: true,
  39991. configurable: true
  39992. });
  39993. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  39994. get: function () {
  39995. return Animation._ANIMATIONTYPE_QUATERNION;
  39996. },
  39997. enumerable: true,
  39998. configurable: true
  39999. });
  40000. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40001. get: function () {
  40002. return Animation._ANIMATIONTYPE_MATRIX;
  40003. },
  40004. enumerable: true,
  40005. configurable: true
  40006. });
  40007. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40008. get: function () {
  40009. return Animation._ANIMATIONTYPE_COLOR3;
  40010. },
  40011. enumerable: true,
  40012. configurable: true
  40013. });
  40014. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40015. get: function () {
  40016. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40017. },
  40018. enumerable: true,
  40019. configurable: true
  40020. });
  40021. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40022. get: function () {
  40023. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40024. },
  40025. enumerable: true,
  40026. configurable: true
  40027. });
  40028. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40029. get: function () {
  40030. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40031. },
  40032. enumerable: true,
  40033. configurable: true
  40034. });
  40035. Animation.Parse = function (parsedAnimation) {
  40036. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40037. var dataType = parsedAnimation.dataType;
  40038. var keys = [];
  40039. var data;
  40040. var index;
  40041. if (parsedAnimation.enableBlending) {
  40042. animation.enableBlending = parsedAnimation.enableBlending;
  40043. }
  40044. if (parsedAnimation.blendingSpeed) {
  40045. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40046. }
  40047. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40048. var key = parsedAnimation.keys[index];
  40049. var inTangent;
  40050. var outTangent;
  40051. switch (dataType) {
  40052. case Animation.ANIMATIONTYPE_FLOAT:
  40053. data = key.values[0];
  40054. if (key.values.length >= 1) {
  40055. inTangent = key.values[1];
  40056. }
  40057. if (key.values.length >= 2) {
  40058. outTangent = key.values[2];
  40059. }
  40060. break;
  40061. case Animation.ANIMATIONTYPE_QUATERNION:
  40062. data = BABYLON.Quaternion.FromArray(key.values);
  40063. if (key.values.length >= 8) {
  40064. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40065. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40066. inTangent = _inTangent;
  40067. }
  40068. }
  40069. if (key.values.length >= 12) {
  40070. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40071. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40072. outTangent = _outTangent;
  40073. }
  40074. }
  40075. break;
  40076. case Animation.ANIMATIONTYPE_MATRIX:
  40077. data = BABYLON.Matrix.FromArray(key.values);
  40078. break;
  40079. case Animation.ANIMATIONTYPE_COLOR3:
  40080. data = BABYLON.Color3.FromArray(key.values);
  40081. break;
  40082. case Animation.ANIMATIONTYPE_VECTOR3:
  40083. default:
  40084. data = BABYLON.Vector3.FromArray(key.values);
  40085. break;
  40086. }
  40087. var keyData = {};
  40088. keyData.frame = key.frame;
  40089. keyData.value = data;
  40090. if (inTangent != undefined) {
  40091. keyData.inTangent = inTangent;
  40092. }
  40093. if (outTangent != undefined) {
  40094. keyData.outTangent = outTangent;
  40095. }
  40096. keys.push(keyData);
  40097. }
  40098. animation.setKeys(keys);
  40099. if (parsedAnimation.ranges) {
  40100. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40101. data = parsedAnimation.ranges[index];
  40102. animation.createRange(data.name, data.from, data.to);
  40103. }
  40104. }
  40105. return animation;
  40106. };
  40107. Animation.AppendSerializedAnimations = function (source, destination) {
  40108. if (source.animations) {
  40109. destination.animations = [];
  40110. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40111. var animation = source.animations[animationIndex];
  40112. destination.animations.push(animation.serialize());
  40113. }
  40114. }
  40115. };
  40116. Animation.AllowMatricesInterpolation = false;
  40117. // Statics
  40118. Animation._ANIMATIONTYPE_FLOAT = 0;
  40119. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40120. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40121. Animation._ANIMATIONTYPE_MATRIX = 3;
  40122. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40123. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40124. Animation._ANIMATIONTYPE_SIZE = 6;
  40125. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40126. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40127. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40128. return Animation;
  40129. }());
  40130. BABYLON.Animation = Animation;
  40131. })(BABYLON || (BABYLON = {}));
  40132. //# sourceMappingURL=babylon.animation.js.map
  40133. var BABYLON;
  40134. (function (BABYLON) {
  40135. var RuntimeAnimation = /** @class */ (function () {
  40136. function RuntimeAnimation(target, animation) {
  40137. this._offsetsCache = {};
  40138. this._highLimitsCache = {};
  40139. this._stopped = false;
  40140. this._blendingFactor = 0;
  40141. this._ratioOffset = 0;
  40142. this._animation = animation;
  40143. this._target = target;
  40144. animation._runtimeAnimations.push(this);
  40145. }
  40146. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40147. get: function () {
  40148. return this._animation;
  40149. },
  40150. enumerable: true,
  40151. configurable: true
  40152. });
  40153. RuntimeAnimation.prototype.reset = function () {
  40154. this._offsetsCache = {};
  40155. this._highLimitsCache = {};
  40156. this.currentFrame = 0;
  40157. this._blendingFactor = 0;
  40158. this._originalBlendValue = null;
  40159. };
  40160. RuntimeAnimation.prototype.isStopped = function () {
  40161. return this._stopped;
  40162. };
  40163. RuntimeAnimation.prototype.dispose = function () {
  40164. var index = this._animation.runtimeAnimations.indexOf(this);
  40165. if (index > -1) {
  40166. this._animation.runtimeAnimations.splice(index, 1);
  40167. }
  40168. };
  40169. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40170. if (typeof value === "function") {
  40171. return value();
  40172. }
  40173. return value;
  40174. };
  40175. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40176. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40177. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40178. }
  40179. this.currentFrame = currentFrame;
  40180. var keys = this._animation.getKeys();
  40181. // Try to get a hash to find the right key
  40182. 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));
  40183. if (keys[startKeyIndex].frame >= currentFrame) {
  40184. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40185. startKeyIndex--;
  40186. }
  40187. }
  40188. for (var key = startKeyIndex; key < keys.length; key++) {
  40189. var endKey = keys[key + 1];
  40190. if (endKey.frame >= currentFrame) {
  40191. var startKey = keys[key];
  40192. var startValue = this._getKeyValue(startKey.value);
  40193. var endValue = this._getKeyValue(endKey.value);
  40194. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40195. var frameDelta = endKey.frame - startKey.frame;
  40196. // gradient : percent of currentFrame between the frame inf and the frame sup
  40197. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40198. // check for easingFunction and correction of gradient
  40199. var easingFunction = this._animation.getEasingFunction();
  40200. if (easingFunction != null) {
  40201. gradient = easingFunction.ease(gradient);
  40202. }
  40203. switch (this._animation.dataType) {
  40204. // Float
  40205. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40206. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40207. switch (loopMode) {
  40208. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40209. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40210. return floatValue;
  40211. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40212. return offsetValue * repeatCount + floatValue;
  40213. }
  40214. break;
  40215. // Quaternion
  40216. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40217. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40218. switch (loopMode) {
  40219. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40220. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40221. return quatValue;
  40222. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40223. return quatValue.add(offsetValue.scale(repeatCount));
  40224. }
  40225. return quatValue;
  40226. // Vector3
  40227. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40228. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40229. switch (loopMode) {
  40230. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40231. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40232. return vec3Value;
  40233. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40234. return vec3Value.add(offsetValue.scale(repeatCount));
  40235. }
  40236. // Vector2
  40237. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40238. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40239. switch (loopMode) {
  40240. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40241. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40242. return vec2Value;
  40243. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40244. return vec2Value.add(offsetValue.scale(repeatCount));
  40245. }
  40246. // Size
  40247. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40248. switch (loopMode) {
  40249. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40250. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40251. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40252. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40253. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40254. }
  40255. // Color3
  40256. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40257. switch (loopMode) {
  40258. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40259. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40260. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40261. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40262. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40263. }
  40264. // Matrix
  40265. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40266. switch (loopMode) {
  40267. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40268. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40269. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40270. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40271. }
  40272. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40273. return startValue;
  40274. }
  40275. default:
  40276. break;
  40277. }
  40278. break;
  40279. }
  40280. }
  40281. return this._getKeyValue(keys[keys.length - 1].value);
  40282. };
  40283. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40284. if (blend === void 0) { blend = false; }
  40285. // Set value
  40286. var path;
  40287. var destination;
  40288. var targetPropertyPath = this._animation.targetPropertyPath;
  40289. if (targetPropertyPath.length > 1) {
  40290. var property = this._target[targetPropertyPath[0]];
  40291. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40292. property = property[targetPropertyPath[index]];
  40293. }
  40294. path = targetPropertyPath[targetPropertyPath.length - 1];
  40295. destination = property;
  40296. }
  40297. else {
  40298. path = targetPropertyPath[0];
  40299. destination = this._target;
  40300. }
  40301. // Blending
  40302. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40303. if (!this._originalBlendValue) {
  40304. if (destination[path].clone) {
  40305. this._originalBlendValue = destination[path].clone();
  40306. }
  40307. else {
  40308. this._originalBlendValue = destination[path];
  40309. }
  40310. }
  40311. if (this._originalBlendValue.prototype) {
  40312. if (this._originalBlendValue.prototype.Lerp) {
  40313. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40314. }
  40315. else {
  40316. destination[path] = currentValue;
  40317. }
  40318. }
  40319. else if (this._originalBlendValue.m) {
  40320. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40321. }
  40322. else {
  40323. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40324. }
  40325. this._blendingFactor += this._animation.blendingSpeed;
  40326. }
  40327. else {
  40328. destination[path] = currentValue;
  40329. }
  40330. if (this._target.markAsDirty) {
  40331. this._target.markAsDirty(this._animation.targetProperty);
  40332. }
  40333. };
  40334. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40335. var keys = this._animation.getKeys();
  40336. if (frame < keys[0].frame) {
  40337. frame = keys[0].frame;
  40338. }
  40339. else if (frame > keys[keys.length - 1].frame) {
  40340. frame = keys[keys.length - 1].frame;
  40341. }
  40342. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40343. this.setValue(currentValue);
  40344. };
  40345. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40346. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40347. this._ratioOffset = this._previousRatio - newRatio;
  40348. };
  40349. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40350. if (blend === void 0) { blend = false; }
  40351. var targetPropertyPath = this._animation.targetPropertyPath;
  40352. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40353. this._stopped = true;
  40354. return false;
  40355. }
  40356. var returnValue = true;
  40357. var keys = this._animation.getKeys();
  40358. // Adding a start key at frame 0 if missing
  40359. if (keys[0].frame !== 0) {
  40360. var newKey = { frame: 0, value: keys[0].value };
  40361. keys.splice(0, 0, newKey);
  40362. }
  40363. // Check limits
  40364. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40365. from = keys[0].frame;
  40366. }
  40367. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40368. to = keys[keys.length - 1].frame;
  40369. }
  40370. //to and from cannot be the same key
  40371. if (from === to) {
  40372. if (from > keys[0].frame) {
  40373. from--;
  40374. }
  40375. else if (to < keys[keys.length - 1].frame) {
  40376. to++;
  40377. }
  40378. }
  40379. // Compute ratio
  40380. var range = to - from;
  40381. var offsetValue;
  40382. // ratio represents the frame delta between from and to
  40383. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40384. var highLimitValue = 0;
  40385. this._previousDelay = delay;
  40386. this._previousRatio = ratio;
  40387. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40388. returnValue = false;
  40389. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40390. }
  40391. else {
  40392. // Get max value if required
  40393. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40394. var keyOffset = to.toString() + from.toString();
  40395. if (!this._offsetsCache[keyOffset]) {
  40396. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40397. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40398. switch (this._animation.dataType) {
  40399. // Float
  40400. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40401. this._offsetsCache[keyOffset] = toValue - fromValue;
  40402. break;
  40403. // Quaternion
  40404. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40405. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40406. break;
  40407. // Vector3
  40408. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40409. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40410. // Vector2
  40411. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40412. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40413. // Size
  40414. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40415. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40416. // Color3
  40417. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40418. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40419. default:
  40420. break;
  40421. }
  40422. this._highLimitsCache[keyOffset] = toValue;
  40423. }
  40424. highLimitValue = this._highLimitsCache[keyOffset];
  40425. offsetValue = this._offsetsCache[keyOffset];
  40426. }
  40427. }
  40428. if (offsetValue === undefined) {
  40429. switch (this._animation.dataType) {
  40430. // Float
  40431. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40432. offsetValue = 0;
  40433. break;
  40434. // Quaternion
  40435. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40436. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40437. break;
  40438. // Vector3
  40439. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40440. offsetValue = BABYLON.Vector3.Zero();
  40441. break;
  40442. // Vector2
  40443. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40444. offsetValue = BABYLON.Vector2.Zero();
  40445. break;
  40446. // Size
  40447. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40448. offsetValue = BABYLON.Size.Zero();
  40449. break;
  40450. // Color3
  40451. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40452. offsetValue = BABYLON.Color3.Black();
  40453. }
  40454. }
  40455. // Compute value
  40456. var repeatCount = (ratio / range) >> 0;
  40457. var currentFrame = returnValue ? from + ratio % range : to;
  40458. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40459. // Set value
  40460. this.setValue(currentValue);
  40461. // Check events
  40462. var events = this._animation.getEvents();
  40463. for (var index = 0; index < events.length; index++) {
  40464. // Make sure current frame has passed event frame and that event frame is within the current range
  40465. // Also, handle both forward and reverse animations
  40466. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40467. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40468. var event = events[index];
  40469. if (!event.isDone) {
  40470. // If event should be done only once, remove it.
  40471. if (event.onlyOnce) {
  40472. events.splice(index, 1);
  40473. index--;
  40474. }
  40475. event.isDone = true;
  40476. event.action();
  40477. } // Don't do anything if the event has already be done.
  40478. }
  40479. else if (events[index].isDone && !events[index].onlyOnce) {
  40480. // reset event, the animation is looping
  40481. events[index].isDone = false;
  40482. }
  40483. }
  40484. if (!returnValue) {
  40485. this._stopped = true;
  40486. }
  40487. return returnValue;
  40488. };
  40489. return RuntimeAnimation;
  40490. }());
  40491. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40492. })(BABYLON || (BABYLON = {}));
  40493. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40494. var BABYLON;
  40495. (function (BABYLON) {
  40496. var Animatable = /** @class */ (function () {
  40497. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40498. if (fromFrame === void 0) { fromFrame = 0; }
  40499. if (toFrame === void 0) { toFrame = 100; }
  40500. if (loopAnimation === void 0) { loopAnimation = false; }
  40501. if (speedRatio === void 0) { speedRatio = 1.0; }
  40502. this.target = target;
  40503. this.fromFrame = fromFrame;
  40504. this.toFrame = toFrame;
  40505. this.loopAnimation = loopAnimation;
  40506. this.onAnimationEnd = onAnimationEnd;
  40507. this._localDelayOffset = null;
  40508. this._pausedDelay = null;
  40509. this._runtimeAnimations = new Array();
  40510. this._paused = false;
  40511. this._speedRatio = 1;
  40512. this.animationStarted = false;
  40513. if (animations) {
  40514. this.appendAnimations(target, animations);
  40515. }
  40516. this._speedRatio = speedRatio;
  40517. this._scene = scene;
  40518. scene._activeAnimatables.push(this);
  40519. }
  40520. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40521. get: function () {
  40522. return this._speedRatio;
  40523. },
  40524. set: function (value) {
  40525. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40526. var animation = this._runtimeAnimations[index];
  40527. animation._prepareForSpeedRatioChange(value);
  40528. }
  40529. this._speedRatio = value;
  40530. },
  40531. enumerable: true,
  40532. configurable: true
  40533. });
  40534. // Methods
  40535. Animatable.prototype.getAnimations = function () {
  40536. return this._runtimeAnimations;
  40537. };
  40538. Animatable.prototype.appendAnimations = function (target, animations) {
  40539. for (var index = 0; index < animations.length; index++) {
  40540. var animation = animations[index];
  40541. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40542. }
  40543. };
  40544. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40545. var runtimeAnimations = this._runtimeAnimations;
  40546. for (var index = 0; index < runtimeAnimations.length; index++) {
  40547. if (runtimeAnimations[index].animation.targetProperty === property) {
  40548. return runtimeAnimations[index].animation;
  40549. }
  40550. }
  40551. return null;
  40552. };
  40553. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40554. var runtimeAnimations = this._runtimeAnimations;
  40555. for (var index = 0; index < runtimeAnimations.length; index++) {
  40556. if (runtimeAnimations[index].animation.targetProperty === property) {
  40557. return runtimeAnimations[index];
  40558. }
  40559. }
  40560. return null;
  40561. };
  40562. Animatable.prototype.reset = function () {
  40563. var runtimeAnimations = this._runtimeAnimations;
  40564. for (var index = 0; index < runtimeAnimations.length; index++) {
  40565. runtimeAnimations[index].reset();
  40566. }
  40567. this._localDelayOffset = null;
  40568. this._pausedDelay = null;
  40569. };
  40570. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40571. var runtimeAnimations = this._runtimeAnimations;
  40572. for (var index = 0; index < runtimeAnimations.length; index++) {
  40573. runtimeAnimations[index].animation.enableBlending = true;
  40574. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40575. }
  40576. };
  40577. Animatable.prototype.disableBlending = function () {
  40578. var runtimeAnimations = this._runtimeAnimations;
  40579. for (var index = 0; index < runtimeAnimations.length; index++) {
  40580. runtimeAnimations[index].animation.enableBlending = false;
  40581. }
  40582. };
  40583. Animatable.prototype.goToFrame = function (frame) {
  40584. var runtimeAnimations = this._runtimeAnimations;
  40585. if (runtimeAnimations[0]) {
  40586. var fps = runtimeAnimations[0].animation.framePerSecond;
  40587. var currentFrame = runtimeAnimations[0].currentFrame;
  40588. var adjustTime = frame - currentFrame;
  40589. var delay = adjustTime * 1000 / fps;
  40590. if (this._localDelayOffset === null) {
  40591. this._localDelayOffset = 0;
  40592. }
  40593. this._localDelayOffset -= delay;
  40594. }
  40595. for (var index = 0; index < runtimeAnimations.length; index++) {
  40596. runtimeAnimations[index].goToFrame(frame);
  40597. }
  40598. };
  40599. Animatable.prototype.pause = function () {
  40600. if (this._paused) {
  40601. return;
  40602. }
  40603. this._paused = true;
  40604. };
  40605. Animatable.prototype.restart = function () {
  40606. this._paused = false;
  40607. };
  40608. Animatable.prototype.stop = function (animationName) {
  40609. if (animationName) {
  40610. var idx = this._scene._activeAnimatables.indexOf(this);
  40611. if (idx > -1) {
  40612. var runtimeAnimations = this._runtimeAnimations;
  40613. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40614. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40615. continue;
  40616. }
  40617. runtimeAnimations[index].dispose();
  40618. runtimeAnimations.splice(index, 1);
  40619. }
  40620. if (runtimeAnimations.length == 0) {
  40621. this._scene._activeAnimatables.splice(idx, 1);
  40622. if (this.onAnimationEnd) {
  40623. this.onAnimationEnd();
  40624. }
  40625. }
  40626. }
  40627. }
  40628. else {
  40629. var index = this._scene._activeAnimatables.indexOf(this);
  40630. if (index > -1) {
  40631. this._scene._activeAnimatables.splice(index, 1);
  40632. var runtimeAnimations = this._runtimeAnimations;
  40633. for (var index = 0; index < runtimeAnimations.length; index++) {
  40634. runtimeAnimations[index].dispose();
  40635. }
  40636. if (this.onAnimationEnd) {
  40637. this.onAnimationEnd();
  40638. }
  40639. }
  40640. }
  40641. };
  40642. Animatable.prototype._animate = function (delay) {
  40643. if (this._paused) {
  40644. this.animationStarted = false;
  40645. if (this._pausedDelay === null) {
  40646. this._pausedDelay = delay;
  40647. }
  40648. return true;
  40649. }
  40650. if (this._localDelayOffset === null) {
  40651. this._localDelayOffset = delay;
  40652. }
  40653. else if (this._pausedDelay !== null) {
  40654. this._localDelayOffset += delay - this._pausedDelay;
  40655. this._pausedDelay = null;
  40656. }
  40657. // Animating
  40658. var running = false;
  40659. var runtimeAnimations = this._runtimeAnimations;
  40660. var index;
  40661. for (index = 0; index < runtimeAnimations.length; index++) {
  40662. var animation = runtimeAnimations[index];
  40663. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  40664. running = running || isRunning;
  40665. }
  40666. this.animationStarted = running;
  40667. if (!running) {
  40668. // Remove from active animatables
  40669. index = this._scene._activeAnimatables.indexOf(this);
  40670. this._scene._activeAnimatables.splice(index, 1);
  40671. // Dispose all runtime animations
  40672. for (index = 0; index < runtimeAnimations.length; index++) {
  40673. runtimeAnimations[index].dispose();
  40674. }
  40675. }
  40676. if (!running && this.onAnimationEnd) {
  40677. this.onAnimationEnd();
  40678. this.onAnimationEnd = null;
  40679. }
  40680. return running;
  40681. };
  40682. return Animatable;
  40683. }());
  40684. BABYLON.Animatable = Animatable;
  40685. })(BABYLON || (BABYLON = {}));
  40686. //# sourceMappingURL=babylon.animatable.js.map
  40687. var BABYLON;
  40688. (function (BABYLON) {
  40689. var EasingFunction = /** @class */ (function () {
  40690. function EasingFunction() {
  40691. // Properties
  40692. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  40693. }
  40694. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  40695. get: function () {
  40696. return EasingFunction._EASINGMODE_EASEIN;
  40697. },
  40698. enumerable: true,
  40699. configurable: true
  40700. });
  40701. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  40702. get: function () {
  40703. return EasingFunction._EASINGMODE_EASEOUT;
  40704. },
  40705. enumerable: true,
  40706. configurable: true
  40707. });
  40708. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  40709. get: function () {
  40710. return EasingFunction._EASINGMODE_EASEINOUT;
  40711. },
  40712. enumerable: true,
  40713. configurable: true
  40714. });
  40715. EasingFunction.prototype.setEasingMode = function (easingMode) {
  40716. var n = Math.min(Math.max(easingMode, 0), 2);
  40717. this._easingMode = n;
  40718. };
  40719. EasingFunction.prototype.getEasingMode = function () {
  40720. return this._easingMode;
  40721. };
  40722. EasingFunction.prototype.easeInCore = function (gradient) {
  40723. throw new Error('You must implement this method');
  40724. };
  40725. EasingFunction.prototype.ease = function (gradient) {
  40726. switch (this._easingMode) {
  40727. case EasingFunction.EASINGMODE_EASEIN:
  40728. return this.easeInCore(gradient);
  40729. case EasingFunction.EASINGMODE_EASEOUT:
  40730. return (1 - this.easeInCore(1 - gradient));
  40731. }
  40732. if (gradient >= 0.5) {
  40733. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  40734. }
  40735. return (this.easeInCore(gradient * 2) * 0.5);
  40736. };
  40737. //Statics
  40738. EasingFunction._EASINGMODE_EASEIN = 0;
  40739. EasingFunction._EASINGMODE_EASEOUT = 1;
  40740. EasingFunction._EASINGMODE_EASEINOUT = 2;
  40741. return EasingFunction;
  40742. }());
  40743. BABYLON.EasingFunction = EasingFunction;
  40744. var CircleEase = /** @class */ (function (_super) {
  40745. __extends(CircleEase, _super);
  40746. function CircleEase() {
  40747. return _super !== null && _super.apply(this, arguments) || this;
  40748. }
  40749. CircleEase.prototype.easeInCore = function (gradient) {
  40750. gradient = Math.max(0, Math.min(1, gradient));
  40751. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  40752. };
  40753. return CircleEase;
  40754. }(EasingFunction));
  40755. BABYLON.CircleEase = CircleEase;
  40756. var BackEase = /** @class */ (function (_super) {
  40757. __extends(BackEase, _super);
  40758. function BackEase(amplitude) {
  40759. if (amplitude === void 0) { amplitude = 1; }
  40760. var _this = _super.call(this) || this;
  40761. _this.amplitude = amplitude;
  40762. return _this;
  40763. }
  40764. BackEase.prototype.easeInCore = function (gradient) {
  40765. var num = Math.max(0, this.amplitude);
  40766. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  40767. };
  40768. return BackEase;
  40769. }(EasingFunction));
  40770. BABYLON.BackEase = BackEase;
  40771. var BounceEase = /** @class */ (function (_super) {
  40772. __extends(BounceEase, _super);
  40773. function BounceEase(bounces, bounciness) {
  40774. if (bounces === void 0) { bounces = 3; }
  40775. if (bounciness === void 0) { bounciness = 2; }
  40776. var _this = _super.call(this) || this;
  40777. _this.bounces = bounces;
  40778. _this.bounciness = bounciness;
  40779. return _this;
  40780. }
  40781. BounceEase.prototype.easeInCore = function (gradient) {
  40782. var y = Math.max(0.0, this.bounces);
  40783. var bounciness = this.bounciness;
  40784. if (bounciness <= 1.0) {
  40785. bounciness = 1.001;
  40786. }
  40787. var num9 = Math.pow(bounciness, y);
  40788. var num5 = 1.0 - bounciness;
  40789. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  40790. var num15 = gradient * num4;
  40791. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  40792. var num3 = Math.floor(num65);
  40793. var num13 = num3 + 1.0;
  40794. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  40795. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  40796. var num7 = (num8 + num12) * 0.5;
  40797. var num6 = gradient - num7;
  40798. var num2 = num7 - num8;
  40799. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  40800. };
  40801. return BounceEase;
  40802. }(EasingFunction));
  40803. BABYLON.BounceEase = BounceEase;
  40804. var CubicEase = /** @class */ (function (_super) {
  40805. __extends(CubicEase, _super);
  40806. function CubicEase() {
  40807. return _super !== null && _super.apply(this, arguments) || this;
  40808. }
  40809. CubicEase.prototype.easeInCore = function (gradient) {
  40810. return (gradient * gradient * gradient);
  40811. };
  40812. return CubicEase;
  40813. }(EasingFunction));
  40814. BABYLON.CubicEase = CubicEase;
  40815. var ElasticEase = /** @class */ (function (_super) {
  40816. __extends(ElasticEase, _super);
  40817. function ElasticEase(oscillations, springiness) {
  40818. if (oscillations === void 0) { oscillations = 3; }
  40819. if (springiness === void 0) { springiness = 3; }
  40820. var _this = _super.call(this) || this;
  40821. _this.oscillations = oscillations;
  40822. _this.springiness = springiness;
  40823. return _this;
  40824. }
  40825. ElasticEase.prototype.easeInCore = function (gradient) {
  40826. var num2;
  40827. var num3 = Math.max(0.0, this.oscillations);
  40828. var num = Math.max(0.0, this.springiness);
  40829. if (num == 0) {
  40830. num2 = gradient;
  40831. }
  40832. else {
  40833. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  40834. }
  40835. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  40836. };
  40837. return ElasticEase;
  40838. }(EasingFunction));
  40839. BABYLON.ElasticEase = ElasticEase;
  40840. var ExponentialEase = /** @class */ (function (_super) {
  40841. __extends(ExponentialEase, _super);
  40842. function ExponentialEase(exponent) {
  40843. if (exponent === void 0) { exponent = 2; }
  40844. var _this = _super.call(this) || this;
  40845. _this.exponent = exponent;
  40846. return _this;
  40847. }
  40848. ExponentialEase.prototype.easeInCore = function (gradient) {
  40849. if (this.exponent <= 0) {
  40850. return gradient;
  40851. }
  40852. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  40853. };
  40854. return ExponentialEase;
  40855. }(EasingFunction));
  40856. BABYLON.ExponentialEase = ExponentialEase;
  40857. var PowerEase = /** @class */ (function (_super) {
  40858. __extends(PowerEase, _super);
  40859. function PowerEase(power) {
  40860. if (power === void 0) { power = 2; }
  40861. var _this = _super.call(this) || this;
  40862. _this.power = power;
  40863. return _this;
  40864. }
  40865. PowerEase.prototype.easeInCore = function (gradient) {
  40866. var y = Math.max(0.0, this.power);
  40867. return Math.pow(gradient, y);
  40868. };
  40869. return PowerEase;
  40870. }(EasingFunction));
  40871. BABYLON.PowerEase = PowerEase;
  40872. var QuadraticEase = /** @class */ (function (_super) {
  40873. __extends(QuadraticEase, _super);
  40874. function QuadraticEase() {
  40875. return _super !== null && _super.apply(this, arguments) || this;
  40876. }
  40877. QuadraticEase.prototype.easeInCore = function (gradient) {
  40878. return (gradient * gradient);
  40879. };
  40880. return QuadraticEase;
  40881. }(EasingFunction));
  40882. BABYLON.QuadraticEase = QuadraticEase;
  40883. var QuarticEase = /** @class */ (function (_super) {
  40884. __extends(QuarticEase, _super);
  40885. function QuarticEase() {
  40886. return _super !== null && _super.apply(this, arguments) || this;
  40887. }
  40888. QuarticEase.prototype.easeInCore = function (gradient) {
  40889. return (gradient * gradient * gradient * gradient);
  40890. };
  40891. return QuarticEase;
  40892. }(EasingFunction));
  40893. BABYLON.QuarticEase = QuarticEase;
  40894. var QuinticEase = /** @class */ (function (_super) {
  40895. __extends(QuinticEase, _super);
  40896. function QuinticEase() {
  40897. return _super !== null && _super.apply(this, arguments) || this;
  40898. }
  40899. QuinticEase.prototype.easeInCore = function (gradient) {
  40900. return (gradient * gradient * gradient * gradient * gradient);
  40901. };
  40902. return QuinticEase;
  40903. }(EasingFunction));
  40904. BABYLON.QuinticEase = QuinticEase;
  40905. var SineEase = /** @class */ (function (_super) {
  40906. __extends(SineEase, _super);
  40907. function SineEase() {
  40908. return _super !== null && _super.apply(this, arguments) || this;
  40909. }
  40910. SineEase.prototype.easeInCore = function (gradient) {
  40911. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  40912. };
  40913. return SineEase;
  40914. }(EasingFunction));
  40915. BABYLON.SineEase = SineEase;
  40916. var BezierCurveEase = /** @class */ (function (_super) {
  40917. __extends(BezierCurveEase, _super);
  40918. function BezierCurveEase(x1, y1, x2, y2) {
  40919. if (x1 === void 0) { x1 = 0; }
  40920. if (y1 === void 0) { y1 = 0; }
  40921. if (x2 === void 0) { x2 = 1; }
  40922. if (y2 === void 0) { y2 = 1; }
  40923. var _this = _super.call(this) || this;
  40924. _this.x1 = x1;
  40925. _this.y1 = y1;
  40926. _this.x2 = x2;
  40927. _this.y2 = y2;
  40928. return _this;
  40929. }
  40930. BezierCurveEase.prototype.easeInCore = function (gradient) {
  40931. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  40932. };
  40933. return BezierCurveEase;
  40934. }(EasingFunction));
  40935. BABYLON.BezierCurveEase = BezierCurveEase;
  40936. })(BABYLON || (BABYLON = {}));
  40937. //# sourceMappingURL=babylon.easing.js.map
  40938. var BABYLON;
  40939. (function (BABYLON) {
  40940. var Condition = /** @class */ (function () {
  40941. function Condition(actionManager) {
  40942. this._actionManager = actionManager;
  40943. }
  40944. Condition.prototype.isValid = function () {
  40945. return true;
  40946. };
  40947. Condition.prototype._getProperty = function (propertyPath) {
  40948. return this._actionManager._getProperty(propertyPath);
  40949. };
  40950. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  40951. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40952. };
  40953. Condition.prototype.serialize = function () {
  40954. };
  40955. Condition.prototype._serialize = function (serializedCondition) {
  40956. return {
  40957. type: 2,
  40958. children: [],
  40959. name: serializedCondition.name,
  40960. properties: serializedCondition.properties
  40961. };
  40962. };
  40963. return Condition;
  40964. }());
  40965. BABYLON.Condition = Condition;
  40966. var ValueCondition = /** @class */ (function (_super) {
  40967. __extends(ValueCondition, _super);
  40968. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  40969. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  40970. var _this = _super.call(this, actionManager) || this;
  40971. _this.propertyPath = propertyPath;
  40972. _this.value = value;
  40973. _this.operator = operator;
  40974. _this._target = target;
  40975. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  40976. _this._property = _this._getProperty(_this.propertyPath);
  40977. return _this;
  40978. }
  40979. Object.defineProperty(ValueCondition, "IsEqual", {
  40980. get: function () {
  40981. return ValueCondition._IsEqual;
  40982. },
  40983. enumerable: true,
  40984. configurable: true
  40985. });
  40986. Object.defineProperty(ValueCondition, "IsDifferent", {
  40987. get: function () {
  40988. return ValueCondition._IsDifferent;
  40989. },
  40990. enumerable: true,
  40991. configurable: true
  40992. });
  40993. Object.defineProperty(ValueCondition, "IsGreater", {
  40994. get: function () {
  40995. return ValueCondition._IsGreater;
  40996. },
  40997. enumerable: true,
  40998. configurable: true
  40999. });
  41000. Object.defineProperty(ValueCondition, "IsLesser", {
  41001. get: function () {
  41002. return ValueCondition._IsLesser;
  41003. },
  41004. enumerable: true,
  41005. configurable: true
  41006. });
  41007. // Methods
  41008. ValueCondition.prototype.isValid = function () {
  41009. switch (this.operator) {
  41010. case ValueCondition.IsGreater:
  41011. return this._effectiveTarget[this._property] > this.value;
  41012. case ValueCondition.IsLesser:
  41013. return this._effectiveTarget[this._property] < this.value;
  41014. case ValueCondition.IsEqual:
  41015. case ValueCondition.IsDifferent:
  41016. var check;
  41017. if (this.value.equals) {
  41018. check = this.value.equals(this._effectiveTarget[this._property]);
  41019. }
  41020. else {
  41021. check = this.value === this._effectiveTarget[this._property];
  41022. }
  41023. return this.operator === ValueCondition.IsEqual ? check : !check;
  41024. }
  41025. return false;
  41026. };
  41027. ValueCondition.prototype.serialize = function () {
  41028. return this._serialize({
  41029. name: "ValueCondition",
  41030. properties: [
  41031. BABYLON.Action._GetTargetProperty(this._target),
  41032. { name: "propertyPath", value: this.propertyPath },
  41033. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41034. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41035. ]
  41036. });
  41037. };
  41038. ValueCondition.GetOperatorName = function (operator) {
  41039. switch (operator) {
  41040. case ValueCondition._IsEqual: return "IsEqual";
  41041. case ValueCondition._IsDifferent: return "IsDifferent";
  41042. case ValueCondition._IsGreater: return "IsGreater";
  41043. case ValueCondition._IsLesser: return "IsLesser";
  41044. default: return "";
  41045. }
  41046. };
  41047. // Statics
  41048. ValueCondition._IsEqual = 0;
  41049. ValueCondition._IsDifferent = 1;
  41050. ValueCondition._IsGreater = 2;
  41051. ValueCondition._IsLesser = 3;
  41052. return ValueCondition;
  41053. }(Condition));
  41054. BABYLON.ValueCondition = ValueCondition;
  41055. var PredicateCondition = /** @class */ (function (_super) {
  41056. __extends(PredicateCondition, _super);
  41057. function PredicateCondition(actionManager, predicate) {
  41058. var _this = _super.call(this, actionManager) || this;
  41059. _this.predicate = predicate;
  41060. return _this;
  41061. }
  41062. PredicateCondition.prototype.isValid = function () {
  41063. return this.predicate();
  41064. };
  41065. return PredicateCondition;
  41066. }(Condition));
  41067. BABYLON.PredicateCondition = PredicateCondition;
  41068. var StateCondition = /** @class */ (function (_super) {
  41069. __extends(StateCondition, _super);
  41070. function StateCondition(actionManager, target, value) {
  41071. var _this = _super.call(this, actionManager) || this;
  41072. _this.value = value;
  41073. _this._target = target;
  41074. return _this;
  41075. }
  41076. // Methods
  41077. StateCondition.prototype.isValid = function () {
  41078. return this._target.state === this.value;
  41079. };
  41080. StateCondition.prototype.serialize = function () {
  41081. return this._serialize({
  41082. name: "StateCondition",
  41083. properties: [
  41084. BABYLON.Action._GetTargetProperty(this._target),
  41085. { name: "value", value: this.value }
  41086. ]
  41087. });
  41088. };
  41089. return StateCondition;
  41090. }(Condition));
  41091. BABYLON.StateCondition = StateCondition;
  41092. })(BABYLON || (BABYLON = {}));
  41093. //# sourceMappingURL=babylon.condition.js.map
  41094. var BABYLON;
  41095. (function (BABYLON) {
  41096. var Action = /** @class */ (function () {
  41097. function Action(triggerOptions, condition) {
  41098. this.triggerOptions = triggerOptions;
  41099. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41100. if (triggerOptions.parameter) {
  41101. this.trigger = triggerOptions.trigger;
  41102. this._triggerParameter = triggerOptions.parameter;
  41103. }
  41104. else {
  41105. this.trigger = triggerOptions;
  41106. }
  41107. this._nextActiveAction = this;
  41108. this._condition = condition;
  41109. }
  41110. // Methods
  41111. Action.prototype._prepare = function () {
  41112. };
  41113. Action.prototype.getTriggerParameter = function () {
  41114. return this._triggerParameter;
  41115. };
  41116. Action.prototype._executeCurrent = function (evt) {
  41117. if (this._nextActiveAction._condition) {
  41118. var condition = this._nextActiveAction._condition;
  41119. var currentRenderId = this._actionManager.getScene().getRenderId();
  41120. // We cache the current evaluation for the current frame
  41121. if (condition._evaluationId === currentRenderId) {
  41122. if (!condition._currentResult) {
  41123. return;
  41124. }
  41125. }
  41126. else {
  41127. condition._evaluationId = currentRenderId;
  41128. if (!condition.isValid()) {
  41129. condition._currentResult = false;
  41130. return;
  41131. }
  41132. condition._currentResult = true;
  41133. }
  41134. }
  41135. this.onBeforeExecuteObservable.notifyObservers(this);
  41136. this._nextActiveAction.execute(evt);
  41137. this.skipToNextActiveAction();
  41138. };
  41139. Action.prototype.execute = function (evt) {
  41140. };
  41141. Action.prototype.skipToNextActiveAction = function () {
  41142. if (this._nextActiveAction._child) {
  41143. if (!this._nextActiveAction._child._actionManager) {
  41144. this._nextActiveAction._child._actionManager = this._actionManager;
  41145. }
  41146. this._nextActiveAction = this._nextActiveAction._child;
  41147. }
  41148. else {
  41149. this._nextActiveAction = this;
  41150. }
  41151. };
  41152. Action.prototype.then = function (action) {
  41153. this._child = action;
  41154. action._actionManager = this._actionManager;
  41155. action._prepare();
  41156. return action;
  41157. };
  41158. Action.prototype._getProperty = function (propertyPath) {
  41159. return this._actionManager._getProperty(propertyPath);
  41160. };
  41161. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41162. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41163. };
  41164. Action.prototype.serialize = function (parent) {
  41165. };
  41166. // Called by BABYLON.Action objects in serialize(...). Internal use
  41167. Action.prototype._serialize = function (serializedAction, parent) {
  41168. var serializationObject = {
  41169. type: 1,
  41170. children: [],
  41171. name: serializedAction.name,
  41172. properties: serializedAction.properties || []
  41173. };
  41174. // Serialize child
  41175. if (this._child) {
  41176. this._child.serialize(serializationObject);
  41177. }
  41178. // Check if "this" has a condition
  41179. if (this._condition) {
  41180. var serializedCondition = this._condition.serialize();
  41181. serializedCondition.children.push(serializationObject);
  41182. if (parent) {
  41183. parent.children.push(serializedCondition);
  41184. }
  41185. return serializedCondition;
  41186. }
  41187. if (parent) {
  41188. parent.children.push(serializationObject);
  41189. }
  41190. return serializationObject;
  41191. };
  41192. Action._SerializeValueAsString = function (value) {
  41193. if (typeof value === "number") {
  41194. return value.toString();
  41195. }
  41196. if (typeof value === "boolean") {
  41197. return value ? "true" : "false";
  41198. }
  41199. if (value instanceof BABYLON.Vector2) {
  41200. return value.x + ", " + value.y;
  41201. }
  41202. if (value instanceof BABYLON.Vector3) {
  41203. return value.x + ", " + value.y + ", " + value.z;
  41204. }
  41205. if (value instanceof BABYLON.Color3) {
  41206. return value.r + ", " + value.g + ", " + value.b;
  41207. }
  41208. if (value instanceof BABYLON.Color4) {
  41209. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41210. }
  41211. return value; // string
  41212. };
  41213. Action._GetTargetProperty = function (target) {
  41214. return {
  41215. name: "target",
  41216. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41217. : target instanceof BABYLON.Light ? "LightProperties"
  41218. : target instanceof BABYLON.Camera ? "CameraProperties"
  41219. : "SceneProperties",
  41220. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41221. };
  41222. };
  41223. return Action;
  41224. }());
  41225. BABYLON.Action = Action;
  41226. })(BABYLON || (BABYLON = {}));
  41227. //# sourceMappingURL=babylon.action.js.map
  41228. var BABYLON;
  41229. (function (BABYLON) {
  41230. /**
  41231. * ActionEvent is the event beint sent when an action is triggered.
  41232. */
  41233. var ActionEvent = /** @class */ (function () {
  41234. /**
  41235. * @param source The mesh or sprite that triggered the action.
  41236. * @param pointerX The X mouse cursor position at the time of the event
  41237. * @param pointerY The Y mouse cursor position at the time of the event
  41238. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41239. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41240. */
  41241. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41242. this.source = source;
  41243. this.pointerX = pointerX;
  41244. this.pointerY = pointerY;
  41245. this.meshUnderPointer = meshUnderPointer;
  41246. this.sourceEvent = sourceEvent;
  41247. this.additionalData = additionalData;
  41248. }
  41249. /**
  41250. * Helper function to auto-create an ActionEvent from a source mesh.
  41251. * @param source The source mesh that triggered the event
  41252. * @param evt {Event} The original (browser) event
  41253. */
  41254. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41255. var scene = source.getScene();
  41256. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41257. };
  41258. /**
  41259. * Helper function to auto-create an ActionEvent from a source mesh.
  41260. * @param source The source sprite that triggered the event
  41261. * @param scene Scene associated with the sprite
  41262. * @param evt {Event} The original (browser) event
  41263. */
  41264. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41265. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41266. };
  41267. /**
  41268. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41269. * @param scene the scene where the event occurred
  41270. * @param evt {Event} The original (browser) event
  41271. */
  41272. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41273. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41274. };
  41275. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41276. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41277. };
  41278. return ActionEvent;
  41279. }());
  41280. BABYLON.ActionEvent = ActionEvent;
  41281. /**
  41282. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41283. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41284. */
  41285. var ActionManager = /** @class */ (function () {
  41286. function ActionManager(scene) {
  41287. // Members
  41288. this.actions = new Array();
  41289. this.hoverCursor = '';
  41290. this._scene = scene;
  41291. scene._actionManagers.push(this);
  41292. }
  41293. Object.defineProperty(ActionManager, "NothingTrigger", {
  41294. get: function () {
  41295. return ActionManager._NothingTrigger;
  41296. },
  41297. enumerable: true,
  41298. configurable: true
  41299. });
  41300. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41301. get: function () {
  41302. return ActionManager._OnPickTrigger;
  41303. },
  41304. enumerable: true,
  41305. configurable: true
  41306. });
  41307. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41308. get: function () {
  41309. return ActionManager._OnLeftPickTrigger;
  41310. },
  41311. enumerable: true,
  41312. configurable: true
  41313. });
  41314. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41315. get: function () {
  41316. return ActionManager._OnRightPickTrigger;
  41317. },
  41318. enumerable: true,
  41319. configurable: true
  41320. });
  41321. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41322. get: function () {
  41323. return ActionManager._OnCenterPickTrigger;
  41324. },
  41325. enumerable: true,
  41326. configurable: true
  41327. });
  41328. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41329. get: function () {
  41330. return ActionManager._OnPickDownTrigger;
  41331. },
  41332. enumerable: true,
  41333. configurable: true
  41334. });
  41335. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41336. get: function () {
  41337. return ActionManager._OnDoublePickTrigger;
  41338. },
  41339. enumerable: true,
  41340. configurable: true
  41341. });
  41342. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41343. get: function () {
  41344. return ActionManager._OnPickUpTrigger;
  41345. },
  41346. enumerable: true,
  41347. configurable: true
  41348. });
  41349. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41350. /// This trigger will only be raised if you also declared a OnPickDown
  41351. get: function () {
  41352. return ActionManager._OnPickOutTrigger;
  41353. },
  41354. enumerable: true,
  41355. configurable: true
  41356. });
  41357. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41358. get: function () {
  41359. return ActionManager._OnLongPressTrigger;
  41360. },
  41361. enumerable: true,
  41362. configurable: true
  41363. });
  41364. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41365. get: function () {
  41366. return ActionManager._OnPointerOverTrigger;
  41367. },
  41368. enumerable: true,
  41369. configurable: true
  41370. });
  41371. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41372. get: function () {
  41373. return ActionManager._OnPointerOutTrigger;
  41374. },
  41375. enumerable: true,
  41376. configurable: true
  41377. });
  41378. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41379. get: function () {
  41380. return ActionManager._OnEveryFrameTrigger;
  41381. },
  41382. enumerable: true,
  41383. configurable: true
  41384. });
  41385. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41386. get: function () {
  41387. return ActionManager._OnIntersectionEnterTrigger;
  41388. },
  41389. enumerable: true,
  41390. configurable: true
  41391. });
  41392. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41393. get: function () {
  41394. return ActionManager._OnIntersectionExitTrigger;
  41395. },
  41396. enumerable: true,
  41397. configurable: true
  41398. });
  41399. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41400. get: function () {
  41401. return ActionManager._OnKeyDownTrigger;
  41402. },
  41403. enumerable: true,
  41404. configurable: true
  41405. });
  41406. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41407. get: function () {
  41408. return ActionManager._OnKeyUpTrigger;
  41409. },
  41410. enumerable: true,
  41411. configurable: true
  41412. });
  41413. // Methods
  41414. ActionManager.prototype.dispose = function () {
  41415. var index = this._scene._actionManagers.indexOf(this);
  41416. for (var i = 0; i < this.actions.length; i++) {
  41417. var action = this.actions[i];
  41418. ActionManager.Triggers[action.trigger]--;
  41419. if (ActionManager.Triggers[action.trigger] === 0) {
  41420. delete ActionManager.Triggers[action.trigger];
  41421. }
  41422. }
  41423. if (index > -1) {
  41424. this._scene._actionManagers.splice(index, 1);
  41425. }
  41426. };
  41427. ActionManager.prototype.getScene = function () {
  41428. return this._scene;
  41429. };
  41430. /**
  41431. * Does this action manager handles actions of any of the given triggers
  41432. * @param {number[]} triggers - the triggers to be tested
  41433. * @return {boolean} whether one (or more) of the triggers is handeled
  41434. */
  41435. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41436. for (var index = 0; index < this.actions.length; index++) {
  41437. var action = this.actions[index];
  41438. if (triggers.indexOf(action.trigger) > -1) {
  41439. return true;
  41440. }
  41441. }
  41442. return false;
  41443. };
  41444. /**
  41445. * Does this action manager handles actions of a given trigger
  41446. * @param {number} trigger - the trigger to be tested
  41447. * @return {boolean} whether the trigger is handeled
  41448. */
  41449. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41450. for (var index = 0; index < this.actions.length; index++) {
  41451. var action = this.actions[index];
  41452. if (action.trigger === trigger) {
  41453. return true;
  41454. }
  41455. }
  41456. return false;
  41457. };
  41458. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41459. /**
  41460. * Does this action manager has pointer triggers
  41461. * @return {boolean} whether or not it has pointer triggers
  41462. */
  41463. get: function () {
  41464. for (var index = 0; index < this.actions.length; index++) {
  41465. var action = this.actions[index];
  41466. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41467. return true;
  41468. }
  41469. }
  41470. return false;
  41471. },
  41472. enumerable: true,
  41473. configurable: true
  41474. });
  41475. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41476. /**
  41477. * Does this action manager has pick triggers
  41478. * @return {boolean} whether or not it has pick triggers
  41479. */
  41480. get: function () {
  41481. for (var index = 0; index < this.actions.length; index++) {
  41482. var action = this.actions[index];
  41483. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41484. return true;
  41485. }
  41486. }
  41487. return false;
  41488. },
  41489. enumerable: true,
  41490. configurable: true
  41491. });
  41492. Object.defineProperty(ActionManager, "HasTriggers", {
  41493. /**
  41494. * Does exist one action manager with at least one trigger
  41495. * @return {boolean} whether or not it exists one action manager with one trigger
  41496. **/
  41497. get: function () {
  41498. for (var t in ActionManager.Triggers) {
  41499. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41500. return true;
  41501. }
  41502. }
  41503. return false;
  41504. },
  41505. enumerable: true,
  41506. configurable: true
  41507. });
  41508. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41509. /**
  41510. * Does exist one action manager with at least one pick trigger
  41511. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41512. **/
  41513. get: function () {
  41514. for (var t in ActionManager.Triggers) {
  41515. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41516. var t_int = parseInt(t);
  41517. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41518. return true;
  41519. }
  41520. }
  41521. }
  41522. return false;
  41523. },
  41524. enumerable: true,
  41525. configurable: true
  41526. });
  41527. /**
  41528. * Does exist one action manager that handles actions of a given trigger
  41529. * @param {number} trigger - the trigger to be tested
  41530. * @return {boolean} whether the trigger is handeled by at least one action manager
  41531. **/
  41532. ActionManager.HasSpecificTrigger = function (trigger) {
  41533. for (var t in ActionManager.Triggers) {
  41534. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41535. var t_int = parseInt(t);
  41536. if (t_int === trigger) {
  41537. return true;
  41538. }
  41539. }
  41540. }
  41541. return false;
  41542. };
  41543. /**
  41544. * Registers an action to this action manager
  41545. * @param {BABYLON.Action} action - the action to be registered
  41546. * @return {BABYLON.Action} the action amended (prepared) after registration
  41547. */
  41548. ActionManager.prototype.registerAction = function (action) {
  41549. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41550. if (this.getScene().actionManager !== this) {
  41551. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41552. return null;
  41553. }
  41554. }
  41555. this.actions.push(action);
  41556. if (ActionManager.Triggers[action.trigger]) {
  41557. ActionManager.Triggers[action.trigger]++;
  41558. }
  41559. else {
  41560. ActionManager.Triggers[action.trigger] = 1;
  41561. }
  41562. action._actionManager = this;
  41563. action._prepare();
  41564. return action;
  41565. };
  41566. /**
  41567. * Process a specific trigger
  41568. * @param {number} trigger - the trigger to process
  41569. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41570. */
  41571. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41572. for (var index = 0; index < this.actions.length; index++) {
  41573. var action = this.actions[index];
  41574. if (action.trigger === trigger) {
  41575. if (evt) {
  41576. if (trigger === ActionManager.OnKeyUpTrigger
  41577. || trigger === ActionManager.OnKeyDownTrigger) {
  41578. var parameter = action.getTriggerParameter();
  41579. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41580. if (!parameter.toLowerCase) {
  41581. continue;
  41582. }
  41583. var lowerCase = parameter.toLowerCase();
  41584. if (lowerCase !== evt.sourceEvent.key) {
  41585. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41586. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41587. if (actualkey !== lowerCase) {
  41588. continue;
  41589. }
  41590. }
  41591. }
  41592. }
  41593. }
  41594. action._executeCurrent(evt);
  41595. }
  41596. }
  41597. };
  41598. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41599. var properties = propertyPath.split(".");
  41600. for (var index = 0; index < properties.length - 1; index++) {
  41601. target = target[properties[index]];
  41602. }
  41603. return target;
  41604. };
  41605. ActionManager.prototype._getProperty = function (propertyPath) {
  41606. var properties = propertyPath.split(".");
  41607. return properties[properties.length - 1];
  41608. };
  41609. ActionManager.prototype.serialize = function (name) {
  41610. var root = {
  41611. children: new Array(),
  41612. name: name,
  41613. type: 3,
  41614. properties: new Array() // Empty for root but required
  41615. };
  41616. for (var i = 0; i < this.actions.length; i++) {
  41617. var triggerObject = {
  41618. type: 0,
  41619. children: new Array(),
  41620. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41621. properties: new Array()
  41622. };
  41623. var triggerOptions = this.actions[i].triggerOptions;
  41624. if (triggerOptions && typeof triggerOptions !== "number") {
  41625. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41626. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41627. }
  41628. else {
  41629. var parameter = {};
  41630. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41631. if (triggerOptions.parameter.mesh) {
  41632. parameter._meshId = triggerOptions.parameter.mesh.id;
  41633. }
  41634. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41635. }
  41636. }
  41637. // Serialize child action, recursively
  41638. this.actions[i].serialize(triggerObject);
  41639. // Add serialized trigger
  41640. root.children.push(triggerObject);
  41641. }
  41642. return root;
  41643. };
  41644. ActionManager.Parse = function (parsedActions, object, scene) {
  41645. var actionManager = new BABYLON.ActionManager(scene);
  41646. if (object === null)
  41647. scene.actionManager = actionManager;
  41648. else
  41649. object.actionManager = actionManager;
  41650. // instanciate a new object
  41651. var instanciate = function (name, params) {
  41652. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  41653. newInstance.constructor.apply(newInstance, params);
  41654. return newInstance;
  41655. };
  41656. var parseParameter = function (name, value, target, propertyPath) {
  41657. if (propertyPath === null) {
  41658. // String, boolean or float
  41659. var floatValue = parseFloat(value);
  41660. if (value === "true" || value === "false")
  41661. return value === "true";
  41662. else
  41663. return isNaN(floatValue) ? value : floatValue;
  41664. }
  41665. var effectiveTarget = propertyPath.split(".");
  41666. var values = value.split(",");
  41667. // Get effective Target
  41668. for (var i = 0; i < effectiveTarget.length; i++) {
  41669. target = target[effectiveTarget[i]];
  41670. }
  41671. // Return appropriate value with its type
  41672. if (typeof (target) === "boolean")
  41673. return values[0] === "true";
  41674. if (typeof (target) === "string")
  41675. return values[0];
  41676. // Parameters with multiple values such as Vector3 etc.
  41677. var split = new Array();
  41678. for (var i = 0; i < values.length; i++)
  41679. split.push(parseFloat(values[i]));
  41680. if (target instanceof BABYLON.Vector3)
  41681. return BABYLON.Vector3.FromArray(split);
  41682. if (target instanceof BABYLON.Vector4)
  41683. return BABYLON.Vector4.FromArray(split);
  41684. if (target instanceof BABYLON.Color3)
  41685. return BABYLON.Color3.FromArray(split);
  41686. if (target instanceof BABYLON.Color4)
  41687. return BABYLON.Color4.FromArray(split);
  41688. return parseFloat(values[0]);
  41689. };
  41690. // traverse graph per trigger
  41691. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  41692. if (combineArray === void 0) { combineArray = null; }
  41693. if (parsedAction.detached)
  41694. return;
  41695. var parameters = new Array();
  41696. var target = null;
  41697. var propertyPath = null;
  41698. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  41699. // Parameters
  41700. if (parsedAction.type === 2)
  41701. parameters.push(actionManager);
  41702. else
  41703. parameters.push(trigger);
  41704. if (combine) {
  41705. var actions = new Array();
  41706. for (var j = 0; j < parsedAction.combine.length; j++) {
  41707. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  41708. }
  41709. parameters.push(actions);
  41710. }
  41711. else {
  41712. for (var i = 0; i < parsedAction.properties.length; i++) {
  41713. var value = parsedAction.properties[i].value;
  41714. var name = parsedAction.properties[i].name;
  41715. var targetType = parsedAction.properties[i].targetType;
  41716. if (name === "target")
  41717. if (targetType !== null && targetType === "SceneProperties")
  41718. value = target = scene;
  41719. else
  41720. value = target = scene.getNodeByName(value);
  41721. else if (name === "parent")
  41722. value = scene.getNodeByName(value);
  41723. else if (name === "sound")
  41724. value = scene.getSoundByName(value);
  41725. else if (name !== "propertyPath") {
  41726. if (parsedAction.type === 2 && name === "operator")
  41727. value = BABYLON.ValueCondition[value];
  41728. else
  41729. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  41730. }
  41731. else {
  41732. propertyPath = value;
  41733. }
  41734. parameters.push(value);
  41735. }
  41736. }
  41737. if (combineArray === null) {
  41738. parameters.push(condition);
  41739. }
  41740. else {
  41741. parameters.push(null);
  41742. }
  41743. // If interpolate value action
  41744. if (parsedAction.name === "InterpolateValueAction") {
  41745. var param = parameters[parameters.length - 2];
  41746. parameters[parameters.length - 1] = param;
  41747. parameters[parameters.length - 2] = condition;
  41748. }
  41749. // Action or condition(s) and not CombineAction
  41750. var newAction = instanciate(parsedAction.name, parameters);
  41751. if (newAction instanceof BABYLON.Condition && condition !== null) {
  41752. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  41753. if (action)
  41754. action.then(nothing);
  41755. else
  41756. actionManager.registerAction(nothing);
  41757. action = nothing;
  41758. }
  41759. if (combineArray === null) {
  41760. if (newAction instanceof BABYLON.Condition) {
  41761. condition = newAction;
  41762. newAction = action;
  41763. }
  41764. else {
  41765. condition = null;
  41766. if (action)
  41767. action.then(newAction);
  41768. else
  41769. actionManager.registerAction(newAction);
  41770. }
  41771. }
  41772. else {
  41773. combineArray.push(newAction);
  41774. }
  41775. for (var i = 0; i < parsedAction.children.length; i++)
  41776. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  41777. };
  41778. // triggers
  41779. for (var i = 0; i < parsedActions.children.length; i++) {
  41780. var triggerParams;
  41781. var trigger = parsedActions.children[i];
  41782. if (trigger.properties.length > 0) {
  41783. var param = trigger.properties[0].value;
  41784. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  41785. if (value._meshId) {
  41786. value.mesh = scene.getMeshByID(value._meshId);
  41787. }
  41788. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  41789. }
  41790. else
  41791. triggerParams = ActionManager[trigger.name];
  41792. for (var j = 0; j < trigger.children.length; j++) {
  41793. if (!trigger.detached)
  41794. traverse(trigger.children[j], triggerParams, null, null);
  41795. }
  41796. }
  41797. };
  41798. ActionManager.GetTriggerName = function (trigger) {
  41799. switch (trigger) {
  41800. case 0: return "NothingTrigger";
  41801. case 1: return "OnPickTrigger";
  41802. case 2: return "OnLeftPickTrigger";
  41803. case 3: return "OnRightPickTrigger";
  41804. case 4: return "OnCenterPickTrigger";
  41805. case 5: return "OnPickDownTrigger";
  41806. case 6: return "OnPickUpTrigger";
  41807. case 7: return "OnLongPressTrigger";
  41808. case 8: return "OnPointerOverTrigger";
  41809. case 9: return "OnPointerOutTrigger";
  41810. case 10: return "OnEveryFrameTrigger";
  41811. case 11: return "OnIntersectionEnterTrigger";
  41812. case 12: return "OnIntersectionExitTrigger";
  41813. case 13: return "OnKeyDownTrigger";
  41814. case 14: return "OnKeyUpTrigger";
  41815. case 15: return "OnPickOutTrigger";
  41816. default: return "";
  41817. }
  41818. };
  41819. // Statics
  41820. ActionManager._NothingTrigger = 0;
  41821. ActionManager._OnPickTrigger = 1;
  41822. ActionManager._OnLeftPickTrigger = 2;
  41823. ActionManager._OnRightPickTrigger = 3;
  41824. ActionManager._OnCenterPickTrigger = 4;
  41825. ActionManager._OnPickDownTrigger = 5;
  41826. ActionManager._OnDoublePickTrigger = 6;
  41827. ActionManager._OnPickUpTrigger = 7;
  41828. ActionManager._OnLongPressTrigger = 8;
  41829. ActionManager._OnPointerOverTrigger = 9;
  41830. ActionManager._OnPointerOutTrigger = 10;
  41831. ActionManager._OnEveryFrameTrigger = 11;
  41832. ActionManager._OnIntersectionEnterTrigger = 12;
  41833. ActionManager._OnIntersectionExitTrigger = 13;
  41834. ActionManager._OnKeyDownTrigger = 14;
  41835. ActionManager._OnKeyUpTrigger = 15;
  41836. ActionManager._OnPickOutTrigger = 16;
  41837. ActionManager.Triggers = {};
  41838. return ActionManager;
  41839. }());
  41840. BABYLON.ActionManager = ActionManager;
  41841. })(BABYLON || (BABYLON = {}));
  41842. //# sourceMappingURL=babylon.actionManager.js.map
  41843. var BABYLON;
  41844. (function (BABYLON) {
  41845. var InterpolateValueAction = /** @class */ (function (_super) {
  41846. __extends(InterpolateValueAction, _super);
  41847. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  41848. if (duration === void 0) { duration = 1000; }
  41849. var _this = _super.call(this, triggerOptions, condition) || this;
  41850. _this.propertyPath = propertyPath;
  41851. _this.value = value;
  41852. _this.duration = duration;
  41853. _this.stopOtherAnimations = stopOtherAnimations;
  41854. _this.onInterpolationDone = onInterpolationDone;
  41855. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  41856. _this._target = _this._effectiveTarget = target;
  41857. return _this;
  41858. }
  41859. InterpolateValueAction.prototype._prepare = function () {
  41860. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41861. this._property = this._getProperty(this.propertyPath);
  41862. };
  41863. InterpolateValueAction.prototype.execute = function () {
  41864. var _this = this;
  41865. var scene = this._actionManager.getScene();
  41866. var keys = [
  41867. {
  41868. frame: 0,
  41869. value: this._effectiveTarget[this._property]
  41870. }, {
  41871. frame: 100,
  41872. value: this.value
  41873. }
  41874. ];
  41875. var dataType;
  41876. if (typeof this.value === "number") {
  41877. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  41878. }
  41879. else if (this.value instanceof BABYLON.Color3) {
  41880. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  41881. }
  41882. else if (this.value instanceof BABYLON.Vector3) {
  41883. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  41884. }
  41885. else if (this.value instanceof BABYLON.Matrix) {
  41886. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  41887. }
  41888. else if (this.value instanceof BABYLON.Quaternion) {
  41889. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  41890. }
  41891. else {
  41892. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  41893. return;
  41894. }
  41895. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  41896. animation.setKeys(keys);
  41897. if (this.stopOtherAnimations) {
  41898. scene.stopAnimation(this._effectiveTarget);
  41899. }
  41900. var wrapper = function () {
  41901. _this.onInterpolationDoneObservable.notifyObservers(_this);
  41902. if (_this.onInterpolationDone) {
  41903. _this.onInterpolationDone();
  41904. }
  41905. };
  41906. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  41907. };
  41908. InterpolateValueAction.prototype.serialize = function (parent) {
  41909. return _super.prototype._serialize.call(this, {
  41910. name: "InterpolateValueAction",
  41911. properties: [
  41912. BABYLON.Action._GetTargetProperty(this._target),
  41913. { name: "propertyPath", value: this.propertyPath },
  41914. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41915. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  41916. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  41917. ]
  41918. }, parent);
  41919. };
  41920. return InterpolateValueAction;
  41921. }(BABYLON.Action));
  41922. BABYLON.InterpolateValueAction = InterpolateValueAction;
  41923. })(BABYLON || (BABYLON = {}));
  41924. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  41925. var BABYLON;
  41926. (function (BABYLON) {
  41927. var SwitchBooleanAction = /** @class */ (function (_super) {
  41928. __extends(SwitchBooleanAction, _super);
  41929. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  41930. var _this = _super.call(this, triggerOptions, condition) || this;
  41931. _this.propertyPath = propertyPath;
  41932. _this._target = _this._effectiveTarget = target;
  41933. return _this;
  41934. }
  41935. SwitchBooleanAction.prototype._prepare = function () {
  41936. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41937. this._property = this._getProperty(this.propertyPath);
  41938. };
  41939. SwitchBooleanAction.prototype.execute = function () {
  41940. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  41941. };
  41942. SwitchBooleanAction.prototype.serialize = function (parent) {
  41943. return _super.prototype._serialize.call(this, {
  41944. name: "SwitchBooleanAction",
  41945. properties: [
  41946. BABYLON.Action._GetTargetProperty(this._target),
  41947. { name: "propertyPath", value: this.propertyPath }
  41948. ]
  41949. }, parent);
  41950. };
  41951. return SwitchBooleanAction;
  41952. }(BABYLON.Action));
  41953. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  41954. var SetStateAction = /** @class */ (function (_super) {
  41955. __extends(SetStateAction, _super);
  41956. function SetStateAction(triggerOptions, target, value, condition) {
  41957. var _this = _super.call(this, triggerOptions, condition) || this;
  41958. _this.value = value;
  41959. _this._target = target;
  41960. return _this;
  41961. }
  41962. SetStateAction.prototype.execute = function () {
  41963. this._target.state = this.value;
  41964. };
  41965. SetStateAction.prototype.serialize = function (parent) {
  41966. return _super.prototype._serialize.call(this, {
  41967. name: "SetStateAction",
  41968. properties: [
  41969. BABYLON.Action._GetTargetProperty(this._target),
  41970. { name: "value", value: this.value }
  41971. ]
  41972. }, parent);
  41973. };
  41974. return SetStateAction;
  41975. }(BABYLON.Action));
  41976. BABYLON.SetStateAction = SetStateAction;
  41977. var SetValueAction = /** @class */ (function (_super) {
  41978. __extends(SetValueAction, _super);
  41979. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  41980. var _this = _super.call(this, triggerOptions, condition) || this;
  41981. _this.propertyPath = propertyPath;
  41982. _this.value = value;
  41983. _this._target = _this._effectiveTarget = target;
  41984. return _this;
  41985. }
  41986. SetValueAction.prototype._prepare = function () {
  41987. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41988. this._property = this._getProperty(this.propertyPath);
  41989. };
  41990. SetValueAction.prototype.execute = function () {
  41991. this._effectiveTarget[this._property] = this.value;
  41992. if (this._target.markAsDirty) {
  41993. this._target.markAsDirty(this._property);
  41994. }
  41995. };
  41996. SetValueAction.prototype.serialize = function (parent) {
  41997. return _super.prototype._serialize.call(this, {
  41998. name: "SetValueAction",
  41999. properties: [
  42000. BABYLON.Action._GetTargetProperty(this._target),
  42001. { name: "propertyPath", value: this.propertyPath },
  42002. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42003. ]
  42004. }, parent);
  42005. };
  42006. return SetValueAction;
  42007. }(BABYLON.Action));
  42008. BABYLON.SetValueAction = SetValueAction;
  42009. var IncrementValueAction = /** @class */ (function (_super) {
  42010. __extends(IncrementValueAction, _super);
  42011. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42012. var _this = _super.call(this, triggerOptions, condition) || this;
  42013. _this.propertyPath = propertyPath;
  42014. _this.value = value;
  42015. _this._target = _this._effectiveTarget = target;
  42016. return _this;
  42017. }
  42018. IncrementValueAction.prototype._prepare = function () {
  42019. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42020. this._property = this._getProperty(this.propertyPath);
  42021. if (typeof this._effectiveTarget[this._property] !== "number") {
  42022. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42023. }
  42024. };
  42025. IncrementValueAction.prototype.execute = function () {
  42026. this._effectiveTarget[this._property] += this.value;
  42027. if (this._target.markAsDirty) {
  42028. this._target.markAsDirty(this._property);
  42029. }
  42030. };
  42031. IncrementValueAction.prototype.serialize = function (parent) {
  42032. return _super.prototype._serialize.call(this, {
  42033. name: "IncrementValueAction",
  42034. properties: [
  42035. BABYLON.Action._GetTargetProperty(this._target),
  42036. { name: "propertyPath", value: this.propertyPath },
  42037. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42038. ]
  42039. }, parent);
  42040. };
  42041. return IncrementValueAction;
  42042. }(BABYLON.Action));
  42043. BABYLON.IncrementValueAction = IncrementValueAction;
  42044. var PlayAnimationAction = /** @class */ (function (_super) {
  42045. __extends(PlayAnimationAction, _super);
  42046. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42047. var _this = _super.call(this, triggerOptions, condition) || this;
  42048. _this.from = from;
  42049. _this.to = to;
  42050. _this.loop = loop;
  42051. _this._target = target;
  42052. return _this;
  42053. }
  42054. PlayAnimationAction.prototype._prepare = function () {
  42055. };
  42056. PlayAnimationAction.prototype.execute = function () {
  42057. var scene = this._actionManager.getScene();
  42058. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42059. };
  42060. PlayAnimationAction.prototype.serialize = function (parent) {
  42061. return _super.prototype._serialize.call(this, {
  42062. name: "PlayAnimationAction",
  42063. properties: [
  42064. BABYLON.Action._GetTargetProperty(this._target),
  42065. { name: "from", value: String(this.from) },
  42066. { name: "to", value: String(this.to) },
  42067. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42068. ]
  42069. }, parent);
  42070. };
  42071. return PlayAnimationAction;
  42072. }(BABYLON.Action));
  42073. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42074. var StopAnimationAction = /** @class */ (function (_super) {
  42075. __extends(StopAnimationAction, _super);
  42076. function StopAnimationAction(triggerOptions, target, condition) {
  42077. var _this = _super.call(this, triggerOptions, condition) || this;
  42078. _this._target = target;
  42079. return _this;
  42080. }
  42081. StopAnimationAction.prototype._prepare = function () {
  42082. };
  42083. StopAnimationAction.prototype.execute = function () {
  42084. var scene = this._actionManager.getScene();
  42085. scene.stopAnimation(this._target);
  42086. };
  42087. StopAnimationAction.prototype.serialize = function (parent) {
  42088. return _super.prototype._serialize.call(this, {
  42089. name: "StopAnimationAction",
  42090. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42091. }, parent);
  42092. };
  42093. return StopAnimationAction;
  42094. }(BABYLON.Action));
  42095. BABYLON.StopAnimationAction = StopAnimationAction;
  42096. var DoNothingAction = /** @class */ (function (_super) {
  42097. __extends(DoNothingAction, _super);
  42098. function DoNothingAction(triggerOptions, condition) {
  42099. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42100. return _super.call(this, triggerOptions, condition) || this;
  42101. }
  42102. DoNothingAction.prototype.execute = function () {
  42103. };
  42104. DoNothingAction.prototype.serialize = function (parent) {
  42105. return _super.prototype._serialize.call(this, {
  42106. name: "DoNothingAction",
  42107. properties: []
  42108. }, parent);
  42109. };
  42110. return DoNothingAction;
  42111. }(BABYLON.Action));
  42112. BABYLON.DoNothingAction = DoNothingAction;
  42113. var CombineAction = /** @class */ (function (_super) {
  42114. __extends(CombineAction, _super);
  42115. function CombineAction(triggerOptions, children, condition) {
  42116. var _this = _super.call(this, triggerOptions, condition) || this;
  42117. _this.children = children;
  42118. return _this;
  42119. }
  42120. CombineAction.prototype._prepare = function () {
  42121. for (var index = 0; index < this.children.length; index++) {
  42122. this.children[index]._actionManager = this._actionManager;
  42123. this.children[index]._prepare();
  42124. }
  42125. };
  42126. CombineAction.prototype.execute = function (evt) {
  42127. for (var index = 0; index < this.children.length; index++) {
  42128. this.children[index].execute(evt);
  42129. }
  42130. };
  42131. CombineAction.prototype.serialize = function (parent) {
  42132. var serializationObject = _super.prototype._serialize.call(this, {
  42133. name: "CombineAction",
  42134. properties: [],
  42135. combine: []
  42136. }, parent);
  42137. for (var i = 0; i < this.children.length; i++) {
  42138. serializationObject.combine.push(this.children[i].serialize(null));
  42139. }
  42140. return serializationObject;
  42141. };
  42142. return CombineAction;
  42143. }(BABYLON.Action));
  42144. BABYLON.CombineAction = CombineAction;
  42145. var ExecuteCodeAction = /** @class */ (function (_super) {
  42146. __extends(ExecuteCodeAction, _super);
  42147. function ExecuteCodeAction(triggerOptions, func, condition) {
  42148. var _this = _super.call(this, triggerOptions, condition) || this;
  42149. _this.func = func;
  42150. return _this;
  42151. }
  42152. ExecuteCodeAction.prototype.execute = function (evt) {
  42153. this.func(evt);
  42154. };
  42155. return ExecuteCodeAction;
  42156. }(BABYLON.Action));
  42157. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42158. var SetParentAction = /** @class */ (function (_super) {
  42159. __extends(SetParentAction, _super);
  42160. function SetParentAction(triggerOptions, target, parent, condition) {
  42161. var _this = _super.call(this, triggerOptions, condition) || this;
  42162. _this._target = target;
  42163. _this._parent = parent;
  42164. return _this;
  42165. }
  42166. SetParentAction.prototype._prepare = function () {
  42167. };
  42168. SetParentAction.prototype.execute = function () {
  42169. if (this._target.parent === this._parent) {
  42170. return;
  42171. }
  42172. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42173. invertParentWorldMatrix.invert();
  42174. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42175. this._target.parent = this._parent;
  42176. };
  42177. SetParentAction.prototype.serialize = function (parent) {
  42178. return _super.prototype._serialize.call(this, {
  42179. name: "SetParentAction",
  42180. properties: [
  42181. BABYLON.Action._GetTargetProperty(this._target),
  42182. BABYLON.Action._GetTargetProperty(this._parent),
  42183. ]
  42184. }, parent);
  42185. };
  42186. return SetParentAction;
  42187. }(BABYLON.Action));
  42188. BABYLON.SetParentAction = SetParentAction;
  42189. var PlaySoundAction = /** @class */ (function (_super) {
  42190. __extends(PlaySoundAction, _super);
  42191. function PlaySoundAction(triggerOptions, sound, condition) {
  42192. var _this = _super.call(this, triggerOptions, condition) || this;
  42193. _this._sound = sound;
  42194. return _this;
  42195. }
  42196. PlaySoundAction.prototype._prepare = function () {
  42197. };
  42198. PlaySoundAction.prototype.execute = function () {
  42199. if (this._sound !== undefined)
  42200. this._sound.play();
  42201. };
  42202. PlaySoundAction.prototype.serialize = function (parent) {
  42203. return _super.prototype._serialize.call(this, {
  42204. name: "PlaySoundAction",
  42205. properties: [{ name: "sound", value: this._sound.name }]
  42206. }, parent);
  42207. };
  42208. return PlaySoundAction;
  42209. }(BABYLON.Action));
  42210. BABYLON.PlaySoundAction = PlaySoundAction;
  42211. var StopSoundAction = /** @class */ (function (_super) {
  42212. __extends(StopSoundAction, _super);
  42213. function StopSoundAction(triggerOptions, sound, condition) {
  42214. var _this = _super.call(this, triggerOptions, condition) || this;
  42215. _this._sound = sound;
  42216. return _this;
  42217. }
  42218. StopSoundAction.prototype._prepare = function () {
  42219. };
  42220. StopSoundAction.prototype.execute = function () {
  42221. if (this._sound !== undefined)
  42222. this._sound.stop();
  42223. };
  42224. StopSoundAction.prototype.serialize = function (parent) {
  42225. return _super.prototype._serialize.call(this, {
  42226. name: "StopSoundAction",
  42227. properties: [{ name: "sound", value: this._sound.name }]
  42228. }, parent);
  42229. };
  42230. return StopSoundAction;
  42231. }(BABYLON.Action));
  42232. BABYLON.StopSoundAction = StopSoundAction;
  42233. })(BABYLON || (BABYLON = {}));
  42234. //# sourceMappingURL=babylon.directActions.js.map
  42235. var BABYLON;
  42236. (function (BABYLON) {
  42237. var SpriteManager = /** @class */ (function () {
  42238. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42239. if (epsilon === void 0) { epsilon = 0.01; }
  42240. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42241. this.name = name;
  42242. this.sprites = new Array();
  42243. this.renderingGroupId = 0;
  42244. this.layerMask = 0x0FFFFFFF;
  42245. this.fogEnabled = true;
  42246. this.isPickable = false;
  42247. /**
  42248. * An event triggered when the manager is disposed.
  42249. * @type {BABYLON.Observable}
  42250. */
  42251. this.onDisposeObservable = new BABYLON.Observable();
  42252. this._vertexBuffers = {};
  42253. this._capacity = capacity;
  42254. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42255. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42256. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42257. if (cellSize.width && cellSize.height) {
  42258. this.cellWidth = cellSize.width;
  42259. this.cellHeight = cellSize.height;
  42260. }
  42261. else if (cellSize !== undefined) {
  42262. this.cellWidth = cellSize;
  42263. this.cellHeight = cellSize;
  42264. }
  42265. else {
  42266. return;
  42267. }
  42268. this._epsilon = epsilon;
  42269. this._scene = scene;
  42270. this._scene.spriteManagers.push(this);
  42271. var indices = [];
  42272. var index = 0;
  42273. for (var count = 0; count < capacity; count++) {
  42274. indices.push(index);
  42275. indices.push(index + 1);
  42276. indices.push(index + 2);
  42277. indices.push(index);
  42278. indices.push(index + 2);
  42279. indices.push(index + 3);
  42280. index += 4;
  42281. }
  42282. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42283. // VBO
  42284. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42285. this._vertexData = new Float32Array(capacity * 16 * 4);
  42286. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42287. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42288. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42289. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42290. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42291. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42292. this._vertexBuffers["options"] = options;
  42293. this._vertexBuffers["cellInfo"] = cellInfo;
  42294. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42295. // Effects
  42296. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42297. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42298. }
  42299. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42300. set: function (callback) {
  42301. if (this._onDisposeObserver) {
  42302. this.onDisposeObservable.remove(this._onDisposeObserver);
  42303. }
  42304. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42305. },
  42306. enumerable: true,
  42307. configurable: true
  42308. });
  42309. Object.defineProperty(SpriteManager.prototype, "texture", {
  42310. get: function () {
  42311. return this._spriteTexture;
  42312. },
  42313. set: function (value) {
  42314. this._spriteTexture = value;
  42315. },
  42316. enumerable: true,
  42317. configurable: true
  42318. });
  42319. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42320. var arrayOffset = index * 16;
  42321. if (offsetX === 0)
  42322. offsetX = this._epsilon;
  42323. else if (offsetX === 1)
  42324. offsetX = 1 - this._epsilon;
  42325. if (offsetY === 0)
  42326. offsetY = this._epsilon;
  42327. else if (offsetY === 1)
  42328. offsetY = 1 - this._epsilon;
  42329. this._vertexData[arrayOffset] = sprite.position.x;
  42330. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42331. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42332. this._vertexData[arrayOffset + 3] = sprite.angle;
  42333. this._vertexData[arrayOffset + 4] = sprite.width;
  42334. this._vertexData[arrayOffset + 5] = sprite.height;
  42335. this._vertexData[arrayOffset + 6] = offsetX;
  42336. this._vertexData[arrayOffset + 7] = offsetY;
  42337. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42338. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42339. var offset = (sprite.cellIndex / rowSize) >> 0;
  42340. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42341. this._vertexData[arrayOffset + 11] = offset;
  42342. // Color
  42343. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42344. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42345. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42346. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42347. };
  42348. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42349. var count = Math.min(this._capacity, this.sprites.length);
  42350. var min = BABYLON.Vector3.Zero();
  42351. var max = BABYLON.Vector3.Zero();
  42352. var distance = Number.MAX_VALUE;
  42353. var currentSprite = null;
  42354. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42355. var cameraView = camera.getViewMatrix();
  42356. for (var index = 0; index < count; index++) {
  42357. var sprite = this.sprites[index];
  42358. if (!sprite) {
  42359. continue;
  42360. }
  42361. if (predicate) {
  42362. if (!predicate(sprite)) {
  42363. continue;
  42364. }
  42365. }
  42366. else if (!sprite.isPickable) {
  42367. continue;
  42368. }
  42369. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42370. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42371. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42372. if (ray.intersectsBoxMinMax(min, max)) {
  42373. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42374. if (distance > currentDistance) {
  42375. distance = currentDistance;
  42376. currentSprite = sprite;
  42377. if (fastCheck) {
  42378. break;
  42379. }
  42380. }
  42381. }
  42382. }
  42383. if (currentSprite) {
  42384. var result = new BABYLON.PickingInfo();
  42385. result.hit = true;
  42386. result.pickedSprite = currentSprite;
  42387. result.distance = distance;
  42388. return result;
  42389. }
  42390. return null;
  42391. };
  42392. SpriteManager.prototype.render = function () {
  42393. // Check
  42394. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42395. return;
  42396. var engine = this._scene.getEngine();
  42397. var baseSize = this._spriteTexture.getBaseSize();
  42398. // Sprites
  42399. var deltaTime = engine.getDeltaTime();
  42400. var max = Math.min(this._capacity, this.sprites.length);
  42401. var rowSize = baseSize.width / this.cellWidth;
  42402. var offset = 0;
  42403. for (var index = 0; index < max; index++) {
  42404. var sprite = this.sprites[index];
  42405. if (!sprite) {
  42406. continue;
  42407. }
  42408. sprite._animate(deltaTime);
  42409. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42410. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42411. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42412. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42413. }
  42414. this._buffer.update(this._vertexData);
  42415. // Render
  42416. var effect = this._effectBase;
  42417. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42418. effect = this._effectFog;
  42419. }
  42420. engine.enableEffect(effect);
  42421. var viewMatrix = this._scene.getViewMatrix();
  42422. effect.setTexture("diffuseSampler", this._spriteTexture);
  42423. effect.setMatrix("view", viewMatrix);
  42424. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42425. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42426. // Fog
  42427. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42428. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42429. effect.setColor3("vFogColor", this._scene.fogColor);
  42430. }
  42431. // VBOs
  42432. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42433. // Draw order
  42434. engine.setDepthFunctionToLessOrEqual();
  42435. effect.setBool("alphaTest", true);
  42436. engine.setColorWrite(false);
  42437. engine.draw(true, 0, max * 6);
  42438. engine.setColorWrite(true);
  42439. effect.setBool("alphaTest", false);
  42440. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42441. engine.draw(true, 0, max * 6);
  42442. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42443. };
  42444. SpriteManager.prototype.dispose = function () {
  42445. if (this._buffer) {
  42446. this._buffer.dispose();
  42447. this._buffer = null;
  42448. }
  42449. if (this._indexBuffer) {
  42450. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42451. this._indexBuffer = null;
  42452. }
  42453. if (this._spriteTexture) {
  42454. this._spriteTexture.dispose();
  42455. this._spriteTexture = null;
  42456. }
  42457. // Remove from scene
  42458. var index = this._scene.spriteManagers.indexOf(this);
  42459. this._scene.spriteManagers.splice(index, 1);
  42460. // Callback
  42461. this.onDisposeObservable.notifyObservers(this);
  42462. this.onDisposeObservable.clear();
  42463. };
  42464. return SpriteManager;
  42465. }());
  42466. BABYLON.SpriteManager = SpriteManager;
  42467. })(BABYLON || (BABYLON = {}));
  42468. //# sourceMappingURL=babylon.spriteManager.js.map
  42469. var BABYLON;
  42470. (function (BABYLON) {
  42471. var Sprite = /** @class */ (function () {
  42472. function Sprite(name, manager) {
  42473. this.name = name;
  42474. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42475. this.width = 1.0;
  42476. this.height = 1.0;
  42477. this.angle = 0;
  42478. this.cellIndex = 0;
  42479. this.invertU = 0;
  42480. this.invertV = 0;
  42481. this.animations = new Array();
  42482. this.isPickable = false;
  42483. this._animationStarted = false;
  42484. this._loopAnimation = false;
  42485. this._fromIndex = 0;
  42486. this._toIndex = 0;
  42487. this._delay = 0;
  42488. this._direction = 1;
  42489. this._time = 0;
  42490. this._manager = manager;
  42491. this._manager.sprites.push(this);
  42492. this.position = BABYLON.Vector3.Zero();
  42493. }
  42494. Object.defineProperty(Sprite.prototype, "size", {
  42495. get: function () {
  42496. return this.width;
  42497. },
  42498. set: function (value) {
  42499. this.width = value;
  42500. this.height = value;
  42501. },
  42502. enumerable: true,
  42503. configurable: true
  42504. });
  42505. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42506. this._fromIndex = from;
  42507. this._toIndex = to;
  42508. this._loopAnimation = loop;
  42509. this._delay = delay;
  42510. this._animationStarted = true;
  42511. this._direction = from < to ? 1 : -1;
  42512. this.cellIndex = from;
  42513. this._time = 0;
  42514. this._onAnimationEnd = onAnimationEnd;
  42515. };
  42516. Sprite.prototype.stopAnimation = function () {
  42517. this._animationStarted = false;
  42518. };
  42519. Sprite.prototype._animate = function (deltaTime) {
  42520. if (!this._animationStarted)
  42521. return;
  42522. this._time += deltaTime;
  42523. if (this._time > this._delay) {
  42524. this._time = this._time % this._delay;
  42525. this.cellIndex += this._direction;
  42526. if (this.cellIndex > this._toIndex) {
  42527. if (this._loopAnimation) {
  42528. this.cellIndex = this._fromIndex;
  42529. }
  42530. else {
  42531. this.cellIndex = this._toIndex;
  42532. this._animationStarted = false;
  42533. if (this._onAnimationEnd) {
  42534. this._onAnimationEnd();
  42535. }
  42536. if (this.disposeWhenFinishedAnimating) {
  42537. this.dispose();
  42538. }
  42539. }
  42540. }
  42541. }
  42542. };
  42543. Sprite.prototype.dispose = function () {
  42544. for (var i = 0; i < this._manager.sprites.length; i++) {
  42545. if (this._manager.sprites[i] == this) {
  42546. this._manager.sprites.splice(i, 1);
  42547. }
  42548. }
  42549. };
  42550. return Sprite;
  42551. }());
  42552. BABYLON.Sprite = Sprite;
  42553. })(BABYLON || (BABYLON = {}));
  42554. //# sourceMappingURL=babylon.sprite.js.map
  42555. var BABYLON;
  42556. (function (BABYLON) {
  42557. var IntersectionInfo = /** @class */ (function () {
  42558. function IntersectionInfo(bu, bv, distance) {
  42559. this.bu = bu;
  42560. this.bv = bv;
  42561. this.distance = distance;
  42562. this.faceId = 0;
  42563. this.subMeshId = 0;
  42564. }
  42565. return IntersectionInfo;
  42566. }());
  42567. BABYLON.IntersectionInfo = IntersectionInfo;
  42568. var PickingInfo = /** @class */ (function () {
  42569. function PickingInfo() {
  42570. this.hit = false;
  42571. this.distance = 0;
  42572. this.pickedPoint = null;
  42573. this.pickedMesh = null;
  42574. this.bu = 0;
  42575. this.bv = 0;
  42576. this.faceId = -1;
  42577. this.subMeshId = 0;
  42578. this.pickedSprite = null;
  42579. }
  42580. // Methods
  42581. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42582. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42583. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42584. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42585. return null;
  42586. }
  42587. var indices = this.pickedMesh.getIndices();
  42588. if (!indices) {
  42589. return null;
  42590. }
  42591. var result;
  42592. if (useVerticesNormals) {
  42593. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42594. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42595. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42596. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42597. normal0 = normal0.scale(this.bu);
  42598. normal1 = normal1.scale(this.bv);
  42599. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42600. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42601. }
  42602. else {
  42603. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42604. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42605. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42606. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42607. var p1p2 = vertex1.subtract(vertex2);
  42608. var p3p2 = vertex3.subtract(vertex2);
  42609. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42610. }
  42611. if (useWorldCoordinates) {
  42612. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42613. }
  42614. return BABYLON.Vector3.Normalize(result);
  42615. };
  42616. PickingInfo.prototype.getTextureCoordinates = function () {
  42617. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42618. return null;
  42619. }
  42620. var indices = this.pickedMesh.getIndices();
  42621. if (!indices) {
  42622. return null;
  42623. }
  42624. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42625. if (!uvs) {
  42626. return null;
  42627. }
  42628. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  42629. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  42630. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  42631. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  42632. uv1 = uv1.scale(this.bu);
  42633. uv2 = uv2.scale(this.bv);
  42634. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  42635. };
  42636. return PickingInfo;
  42637. }());
  42638. BABYLON.PickingInfo = PickingInfo;
  42639. })(BABYLON || (BABYLON = {}));
  42640. //# sourceMappingURL=babylon.pickingInfo.js.map
  42641. var BABYLON;
  42642. (function (BABYLON) {
  42643. var Ray = /** @class */ (function () {
  42644. function Ray(origin, direction, length) {
  42645. if (length === void 0) { length = Number.MAX_VALUE; }
  42646. this.origin = origin;
  42647. this.direction = direction;
  42648. this.length = length;
  42649. }
  42650. // Methods
  42651. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  42652. var d = 0.0;
  42653. var maxValue = Number.MAX_VALUE;
  42654. var inv;
  42655. var min;
  42656. var max;
  42657. var temp;
  42658. if (Math.abs(this.direction.x) < 0.0000001) {
  42659. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  42660. return false;
  42661. }
  42662. }
  42663. else {
  42664. inv = 1.0 / this.direction.x;
  42665. min = (minimum.x - this.origin.x) * inv;
  42666. max = (maximum.x - this.origin.x) * inv;
  42667. if (max === -Infinity) {
  42668. max = Infinity;
  42669. }
  42670. if (min > max) {
  42671. temp = min;
  42672. min = max;
  42673. max = temp;
  42674. }
  42675. d = Math.max(min, d);
  42676. maxValue = Math.min(max, maxValue);
  42677. if (d > maxValue) {
  42678. return false;
  42679. }
  42680. }
  42681. if (Math.abs(this.direction.y) < 0.0000001) {
  42682. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  42683. return false;
  42684. }
  42685. }
  42686. else {
  42687. inv = 1.0 / this.direction.y;
  42688. min = (minimum.y - this.origin.y) * inv;
  42689. max = (maximum.y - this.origin.y) * inv;
  42690. if (max === -Infinity) {
  42691. max = Infinity;
  42692. }
  42693. if (min > max) {
  42694. temp = min;
  42695. min = max;
  42696. max = temp;
  42697. }
  42698. d = Math.max(min, d);
  42699. maxValue = Math.min(max, maxValue);
  42700. if (d > maxValue) {
  42701. return false;
  42702. }
  42703. }
  42704. if (Math.abs(this.direction.z) < 0.0000001) {
  42705. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  42706. return false;
  42707. }
  42708. }
  42709. else {
  42710. inv = 1.0 / this.direction.z;
  42711. min = (minimum.z - this.origin.z) * inv;
  42712. max = (maximum.z - this.origin.z) * inv;
  42713. if (max === -Infinity) {
  42714. max = Infinity;
  42715. }
  42716. if (min > max) {
  42717. temp = min;
  42718. min = max;
  42719. max = temp;
  42720. }
  42721. d = Math.max(min, d);
  42722. maxValue = Math.min(max, maxValue);
  42723. if (d > maxValue) {
  42724. return false;
  42725. }
  42726. }
  42727. return true;
  42728. };
  42729. Ray.prototype.intersectsBox = function (box) {
  42730. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  42731. };
  42732. Ray.prototype.intersectsSphere = function (sphere) {
  42733. var x = sphere.center.x - this.origin.x;
  42734. var y = sphere.center.y - this.origin.y;
  42735. var z = sphere.center.z - this.origin.z;
  42736. var pyth = (x * x) + (y * y) + (z * z);
  42737. var rr = sphere.radius * sphere.radius;
  42738. if (pyth <= rr) {
  42739. return true;
  42740. }
  42741. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  42742. if (dot < 0.0) {
  42743. return false;
  42744. }
  42745. var temp = pyth - (dot * dot);
  42746. return temp <= rr;
  42747. };
  42748. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  42749. if (!this._edge1) {
  42750. this._edge1 = BABYLON.Vector3.Zero();
  42751. this._edge2 = BABYLON.Vector3.Zero();
  42752. this._pvec = BABYLON.Vector3.Zero();
  42753. this._tvec = BABYLON.Vector3.Zero();
  42754. this._qvec = BABYLON.Vector3.Zero();
  42755. }
  42756. vertex1.subtractToRef(vertex0, this._edge1);
  42757. vertex2.subtractToRef(vertex0, this._edge2);
  42758. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  42759. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  42760. if (det === 0) {
  42761. return null;
  42762. }
  42763. var invdet = 1 / det;
  42764. this.origin.subtractToRef(vertex0, this._tvec);
  42765. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  42766. if (bu < 0 || bu > 1.0) {
  42767. return null;
  42768. }
  42769. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  42770. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  42771. if (bv < 0 || bu + bv > 1.0) {
  42772. return null;
  42773. }
  42774. //check if the distance is longer than the predefined length.
  42775. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  42776. if (distance > this.length) {
  42777. return null;
  42778. }
  42779. return new BABYLON.IntersectionInfo(bu, bv, distance);
  42780. };
  42781. Ray.prototype.intersectsPlane = function (plane) {
  42782. var distance;
  42783. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  42784. if (Math.abs(result1) < 9.99999997475243E-07) {
  42785. return null;
  42786. }
  42787. else {
  42788. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  42789. distance = (-plane.d - result2) / result1;
  42790. if (distance < 0.0) {
  42791. if (distance < -9.99999997475243E-07) {
  42792. return null;
  42793. }
  42794. else {
  42795. return 0;
  42796. }
  42797. }
  42798. return distance;
  42799. }
  42800. };
  42801. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  42802. var tm = BABYLON.Tmp.Matrix[0];
  42803. mesh.getWorldMatrix().invertToRef(tm);
  42804. if (this._tmpRay) {
  42805. Ray.TransformToRef(this, tm, this._tmpRay);
  42806. }
  42807. else {
  42808. this._tmpRay = Ray.Transform(this, tm);
  42809. }
  42810. return mesh.intersects(this._tmpRay, fastCheck);
  42811. };
  42812. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  42813. if (results) {
  42814. results.length = 0;
  42815. }
  42816. else {
  42817. results = [];
  42818. }
  42819. for (var i = 0; i < meshes.length; i++) {
  42820. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  42821. if (pickInfo.hit) {
  42822. results.push(pickInfo);
  42823. }
  42824. }
  42825. results.sort(this._comparePickingInfo);
  42826. return results;
  42827. };
  42828. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  42829. if (pickingInfoA.distance < pickingInfoB.distance) {
  42830. return -1;
  42831. }
  42832. else if (pickingInfoA.distance > pickingInfoB.distance) {
  42833. return 1;
  42834. }
  42835. else {
  42836. return 0;
  42837. }
  42838. };
  42839. /**
  42840. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  42841. * @param sega the first point of the segment to test the intersection against
  42842. * @param segb the second point of the segment to test the intersection against
  42843. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  42844. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  42845. */
  42846. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  42847. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  42848. var u = segb.subtract(sega);
  42849. var v = rsegb.subtract(this.origin);
  42850. var w = sega.subtract(this.origin);
  42851. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  42852. var b = BABYLON.Vector3.Dot(u, v);
  42853. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  42854. var d = BABYLON.Vector3.Dot(u, w);
  42855. var e = BABYLON.Vector3.Dot(v, w);
  42856. var D = a * c - b * b; // always >= 0
  42857. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  42858. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  42859. // compute the line parameters of the two closest points
  42860. if (D < Ray.smallnum) {
  42861. sN = 0.0; // force using point P0 on segment S1
  42862. sD = 1.0; // to prevent possible division by 0.0 later
  42863. tN = e;
  42864. tD = c;
  42865. }
  42866. else {
  42867. sN = (b * e - c * d);
  42868. tN = (a * e - b * d);
  42869. if (sN < 0.0) {
  42870. sN = 0.0;
  42871. tN = e;
  42872. tD = c;
  42873. }
  42874. else if (sN > sD) {
  42875. sN = sD;
  42876. tN = e + b;
  42877. tD = c;
  42878. }
  42879. }
  42880. if (tN < 0.0) {
  42881. tN = 0.0;
  42882. // recompute sc for this edge
  42883. if (-d < 0.0) {
  42884. sN = 0.0;
  42885. }
  42886. else if (-d > a)
  42887. sN = sD;
  42888. else {
  42889. sN = -d;
  42890. sD = a;
  42891. }
  42892. }
  42893. else if (tN > tD) {
  42894. tN = tD;
  42895. // recompute sc for this edge
  42896. if ((-d + b) < 0.0) {
  42897. sN = 0;
  42898. }
  42899. else if ((-d + b) > a) {
  42900. sN = sD;
  42901. }
  42902. else {
  42903. sN = (-d + b);
  42904. sD = a;
  42905. }
  42906. }
  42907. // finally do the division to get sc and tc
  42908. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  42909. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  42910. // get the difference of the two closest points
  42911. var qtc = v.multiplyByFloats(tc, tc, tc);
  42912. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  42913. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  42914. if (isIntersected) {
  42915. return qtc.length();
  42916. }
  42917. return -1;
  42918. };
  42919. // Statics
  42920. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  42921. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  42922. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  42923. var direction = end.subtract(start);
  42924. direction.normalize();
  42925. return new Ray(start, direction);
  42926. };
  42927. /**
  42928. * 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
  42929. * transformed to the given world matrix.
  42930. * @param origin The origin point
  42931. * @param end The end point
  42932. * @param world a matrix to transform the ray to. Default is the identity matrix.
  42933. */
  42934. Ray.CreateNewFromTo = function (origin, end, world) {
  42935. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  42936. var direction = end.subtract(origin);
  42937. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  42938. direction.normalize();
  42939. return Ray.Transform(new Ray(origin, direction, length), world);
  42940. };
  42941. Ray.Transform = function (ray, matrix) {
  42942. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  42943. Ray.TransformToRef(ray, matrix, result);
  42944. return result;
  42945. };
  42946. Ray.TransformToRef = function (ray, matrix, result) {
  42947. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  42948. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  42949. result.length = ray.length;
  42950. var dir = result.direction;
  42951. var len = dir.length();
  42952. if (!(len === 0 || len === 1)) {
  42953. var num = 1.0 / len;
  42954. dir.x *= num;
  42955. dir.y *= num;
  42956. dir.z *= num;
  42957. result.length *= len;
  42958. }
  42959. };
  42960. Ray.smallnum = 0.00000001;
  42961. Ray.rayl = 10e8;
  42962. return Ray;
  42963. }());
  42964. BABYLON.Ray = Ray;
  42965. })(BABYLON || (BABYLON = {}));
  42966. //# sourceMappingURL=babylon.ray.js.map
  42967. var BABYLON;
  42968. (function (BABYLON) {
  42969. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  42970. if (boxMin.x > sphereCenter.x + sphereRadius)
  42971. return false;
  42972. if (sphereCenter.x - sphereRadius > boxMax.x)
  42973. return false;
  42974. if (boxMin.y > sphereCenter.y + sphereRadius)
  42975. return false;
  42976. if (sphereCenter.y - sphereRadius > boxMax.y)
  42977. return false;
  42978. if (boxMin.z > sphereCenter.z + sphereRadius)
  42979. return false;
  42980. if (sphereCenter.z - sphereRadius > boxMax.z)
  42981. return false;
  42982. return true;
  42983. };
  42984. var getLowestRoot = (function () {
  42985. var result = { root: 0, found: false };
  42986. return function (a, b, c, maxR) {
  42987. result.root = 0;
  42988. result.found = false;
  42989. var determinant = b * b - 4.0 * a * c;
  42990. if (determinant < 0)
  42991. return result;
  42992. var sqrtD = Math.sqrt(determinant);
  42993. var r1 = (-b - sqrtD) / (2.0 * a);
  42994. var r2 = (-b + sqrtD) / (2.0 * a);
  42995. if (r1 > r2) {
  42996. var temp = r2;
  42997. r2 = r1;
  42998. r1 = temp;
  42999. }
  43000. if (r1 > 0 && r1 < maxR) {
  43001. result.root = r1;
  43002. result.found = true;
  43003. return result;
  43004. }
  43005. if (r2 > 0 && r2 < maxR) {
  43006. result.root = r2;
  43007. result.found = true;
  43008. return result;
  43009. }
  43010. return result;
  43011. };
  43012. })();
  43013. var Collider = /** @class */ (function () {
  43014. function Collider() {
  43015. this.radius = BABYLON.Vector3.One();
  43016. this.retry = 0;
  43017. this.basePointWorld = BABYLON.Vector3.Zero();
  43018. this.velocityWorld = BABYLON.Vector3.Zero();
  43019. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43020. this._collisionPoint = BABYLON.Vector3.Zero();
  43021. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43022. this._tempVector = BABYLON.Vector3.Zero();
  43023. this._tempVector2 = BABYLON.Vector3.Zero();
  43024. this._tempVector3 = BABYLON.Vector3.Zero();
  43025. this._tempVector4 = BABYLON.Vector3.Zero();
  43026. this._edge = BABYLON.Vector3.Zero();
  43027. this._baseToVertex = BABYLON.Vector3.Zero();
  43028. this._destinationPoint = BABYLON.Vector3.Zero();
  43029. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43030. this._displacementVector = BABYLON.Vector3.Zero();
  43031. this._collisionMask = -1;
  43032. }
  43033. Object.defineProperty(Collider.prototype, "collisionMask", {
  43034. get: function () {
  43035. return this._collisionMask;
  43036. },
  43037. set: function (mask) {
  43038. this._collisionMask = !isNaN(mask) ? mask : -1;
  43039. },
  43040. enumerable: true,
  43041. configurable: true
  43042. });
  43043. // Methods
  43044. Collider.prototype._initialize = function (source, dir, e) {
  43045. this.velocity = dir;
  43046. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43047. this.basePoint = source;
  43048. source.multiplyToRef(this.radius, this.basePointWorld);
  43049. dir.multiplyToRef(this.radius, this.velocityWorld);
  43050. this.velocityWorldLength = this.velocityWorld.length();
  43051. this.epsilon = e;
  43052. this.collisionFound = false;
  43053. };
  43054. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43055. pa.subtractToRef(point, this._tempVector);
  43056. pb.subtractToRef(point, this._tempVector2);
  43057. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43058. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43059. if (d < 0)
  43060. return false;
  43061. pc.subtractToRef(point, this._tempVector3);
  43062. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43063. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43064. if (d < 0)
  43065. return false;
  43066. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43067. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43068. return d >= 0;
  43069. };
  43070. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43071. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43072. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43073. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43074. return false;
  43075. }
  43076. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43077. return false;
  43078. return true;
  43079. };
  43080. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43081. var t0;
  43082. var embeddedInPlane = false;
  43083. //defensive programming, actually not needed.
  43084. if (!trianglePlaneArray) {
  43085. trianglePlaneArray = [];
  43086. }
  43087. if (!trianglePlaneArray[faceIndex]) {
  43088. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43089. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43090. }
  43091. var trianglePlane = trianglePlaneArray[faceIndex];
  43092. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43093. return;
  43094. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43095. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43096. if (normalDotVelocity == 0) {
  43097. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43098. return;
  43099. embeddedInPlane = true;
  43100. t0 = 0;
  43101. }
  43102. else {
  43103. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43104. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43105. if (t0 > t1) {
  43106. var temp = t1;
  43107. t1 = t0;
  43108. t0 = temp;
  43109. }
  43110. if (t0 > 1.0 || t1 < 0.0)
  43111. return;
  43112. if (t0 < 0)
  43113. t0 = 0;
  43114. if (t0 > 1.0)
  43115. t0 = 1.0;
  43116. }
  43117. this._collisionPoint.copyFromFloats(0, 0, 0);
  43118. var found = false;
  43119. var t = 1.0;
  43120. if (!embeddedInPlane) {
  43121. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43122. this.velocity.scaleToRef(t0, this._tempVector);
  43123. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43124. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43125. found = true;
  43126. t = t0;
  43127. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43128. }
  43129. }
  43130. if (!found) {
  43131. var velocitySquaredLength = this.velocity.lengthSquared();
  43132. var a = velocitySquaredLength;
  43133. this.basePoint.subtractToRef(p1, this._tempVector);
  43134. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43135. var c = this._tempVector.lengthSquared() - 1.0;
  43136. var lowestRoot = getLowestRoot(a, b, c, t);
  43137. if (lowestRoot.found) {
  43138. t = lowestRoot.root;
  43139. found = true;
  43140. this._collisionPoint.copyFrom(p1);
  43141. }
  43142. this.basePoint.subtractToRef(p2, this._tempVector);
  43143. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43144. c = this._tempVector.lengthSquared() - 1.0;
  43145. lowestRoot = getLowestRoot(a, b, c, t);
  43146. if (lowestRoot.found) {
  43147. t = lowestRoot.root;
  43148. found = true;
  43149. this._collisionPoint.copyFrom(p2);
  43150. }
  43151. this.basePoint.subtractToRef(p3, this._tempVector);
  43152. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43153. c = this._tempVector.lengthSquared() - 1.0;
  43154. lowestRoot = getLowestRoot(a, b, c, t);
  43155. if (lowestRoot.found) {
  43156. t = lowestRoot.root;
  43157. found = true;
  43158. this._collisionPoint.copyFrom(p3);
  43159. }
  43160. p2.subtractToRef(p1, this._edge);
  43161. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43162. var edgeSquaredLength = this._edge.lengthSquared();
  43163. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43164. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43165. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43166. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43167. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43168. lowestRoot = getLowestRoot(a, b, c, t);
  43169. if (lowestRoot.found) {
  43170. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43171. if (f >= 0.0 && f <= 1.0) {
  43172. t = lowestRoot.root;
  43173. found = true;
  43174. this._edge.scaleInPlace(f);
  43175. p1.addToRef(this._edge, this._collisionPoint);
  43176. }
  43177. }
  43178. p3.subtractToRef(p2, this._edge);
  43179. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43180. edgeSquaredLength = this._edge.lengthSquared();
  43181. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43182. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43183. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43184. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43185. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43186. lowestRoot = getLowestRoot(a, b, c, t);
  43187. if (lowestRoot.found) {
  43188. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43189. if (f >= 0.0 && f <= 1.0) {
  43190. t = lowestRoot.root;
  43191. found = true;
  43192. this._edge.scaleInPlace(f);
  43193. p2.addToRef(this._edge, this._collisionPoint);
  43194. }
  43195. }
  43196. p1.subtractToRef(p3, this._edge);
  43197. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43198. edgeSquaredLength = this._edge.lengthSquared();
  43199. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43200. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43201. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43202. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43203. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43204. lowestRoot = getLowestRoot(a, b, c, t);
  43205. if (lowestRoot.found) {
  43206. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43207. if (f >= 0.0 && f <= 1.0) {
  43208. t = lowestRoot.root;
  43209. found = true;
  43210. this._edge.scaleInPlace(f);
  43211. p3.addToRef(this._edge, this._collisionPoint);
  43212. }
  43213. }
  43214. }
  43215. if (found) {
  43216. var distToCollision = t * this.velocity.length();
  43217. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43218. if (!this.intersectionPoint) {
  43219. this.intersectionPoint = this._collisionPoint.clone();
  43220. }
  43221. else {
  43222. this.intersectionPoint.copyFrom(this._collisionPoint);
  43223. }
  43224. this.nearestDistance = distToCollision;
  43225. this.collisionFound = true;
  43226. }
  43227. }
  43228. };
  43229. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43230. for (var i = indexStart; i < indexEnd; i += 3) {
  43231. var p1 = pts[indices[i] - decal];
  43232. var p2 = pts[indices[i + 1] - decal];
  43233. var p3 = pts[indices[i + 2] - decal];
  43234. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43235. }
  43236. };
  43237. Collider.prototype._getResponse = function (pos, vel) {
  43238. pos.addToRef(vel, this._destinationPoint);
  43239. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43240. this.basePoint.addToRef(vel, pos);
  43241. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43242. this._slidePlaneNormal.normalize();
  43243. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43244. pos.addInPlace(this._displacementVector);
  43245. this.intersectionPoint.addInPlace(this._displacementVector);
  43246. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43247. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43248. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43249. };
  43250. return Collider;
  43251. }());
  43252. BABYLON.Collider = Collider;
  43253. })(BABYLON || (BABYLON = {}));
  43254. //# sourceMappingURL=babylon.collider.js.map
  43255. var BABYLON;
  43256. (function (BABYLON) {
  43257. //WebWorker code will be inserted to this variable.
  43258. BABYLON.CollisionWorker = "";
  43259. var WorkerTaskType;
  43260. (function (WorkerTaskType) {
  43261. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43262. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43263. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43264. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43265. var WorkerReplyType;
  43266. (function (WorkerReplyType) {
  43267. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43268. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43269. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43270. var CollisionCoordinatorWorker = /** @class */ (function () {
  43271. function CollisionCoordinatorWorker() {
  43272. var _this = this;
  43273. this._scaledPosition = BABYLON.Vector3.Zero();
  43274. this._scaledVelocity = BABYLON.Vector3.Zero();
  43275. this.onMeshUpdated = function (mesh) {
  43276. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43277. };
  43278. this.onGeometryUpdated = function (geometry) {
  43279. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43280. };
  43281. this._afterRender = function () {
  43282. if (!_this._init)
  43283. return;
  43284. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43285. return;
  43286. }
  43287. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43288. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43289. if (_this._runningUpdated > 4) {
  43290. return;
  43291. }
  43292. ++_this._runningUpdated;
  43293. var payload = {
  43294. updatedMeshes: _this._addUpdateMeshesList,
  43295. updatedGeometries: _this._addUpdateGeometriesList,
  43296. removedGeometries: _this._toRemoveGeometryArray,
  43297. removedMeshes: _this._toRemoveMeshesArray
  43298. };
  43299. var message = {
  43300. payload: payload,
  43301. taskType: WorkerTaskType.UPDATE
  43302. };
  43303. var serializable = [];
  43304. for (var id in payload.updatedGeometries) {
  43305. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43306. //prepare transferables
  43307. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43308. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43309. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43310. }
  43311. }
  43312. _this._worker.postMessage(message, serializable);
  43313. _this._addUpdateMeshesList = {};
  43314. _this._addUpdateGeometriesList = {};
  43315. _this._toRemoveGeometryArray = [];
  43316. _this._toRemoveMeshesArray = [];
  43317. };
  43318. this._onMessageFromWorker = function (e) {
  43319. var returnData = e.data;
  43320. if (returnData.error != WorkerReplyType.SUCCESS) {
  43321. //TODO what errors can be returned from the worker?
  43322. BABYLON.Tools.Warn("error returned from worker!");
  43323. return;
  43324. }
  43325. switch (returnData.taskType) {
  43326. case WorkerTaskType.INIT:
  43327. _this._init = true;
  43328. //Update the worked with ALL of the scene's current state
  43329. _this._scene.meshes.forEach(function (mesh) {
  43330. _this.onMeshAdded(mesh);
  43331. });
  43332. _this._scene.getGeometries().forEach(function (geometry) {
  43333. _this.onGeometryAdded(geometry);
  43334. });
  43335. break;
  43336. case WorkerTaskType.UPDATE:
  43337. _this._runningUpdated--;
  43338. break;
  43339. case WorkerTaskType.COLLIDE:
  43340. _this._runningCollisionTask = false;
  43341. var returnPayload = returnData.payload;
  43342. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43343. return;
  43344. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43345. if (callback) {
  43346. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43347. if (mesh) {
  43348. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43349. }
  43350. }
  43351. //cleanup
  43352. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43353. break;
  43354. }
  43355. };
  43356. this._collisionsCallbackArray = [];
  43357. this._init = false;
  43358. this._runningUpdated = 0;
  43359. this._runningCollisionTask = false;
  43360. this._addUpdateMeshesList = {};
  43361. this._addUpdateGeometriesList = {};
  43362. this._toRemoveGeometryArray = [];
  43363. this._toRemoveMeshesArray = [];
  43364. }
  43365. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43366. if (!this._init)
  43367. return;
  43368. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43369. return;
  43370. position.divideToRef(collider.radius, this._scaledPosition);
  43371. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43372. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43373. var payload = {
  43374. collider: {
  43375. position: this._scaledPosition.asArray(),
  43376. velocity: this._scaledVelocity.asArray(),
  43377. radius: collider.radius.asArray()
  43378. },
  43379. collisionId: collisionIndex,
  43380. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43381. maximumRetry: maximumRetry
  43382. };
  43383. var message = {
  43384. payload: payload,
  43385. taskType: WorkerTaskType.COLLIDE
  43386. };
  43387. this._worker.postMessage(message);
  43388. };
  43389. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43390. this._scene = scene;
  43391. this._scene.registerAfterRender(this._afterRender);
  43392. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43393. this._worker = new Worker(workerUrl);
  43394. this._worker.onmessage = this._onMessageFromWorker;
  43395. var message = {
  43396. payload: {},
  43397. taskType: WorkerTaskType.INIT
  43398. };
  43399. this._worker.postMessage(message);
  43400. };
  43401. CollisionCoordinatorWorker.prototype.destroy = function () {
  43402. this._scene.unregisterAfterRender(this._afterRender);
  43403. this._worker.terminate();
  43404. };
  43405. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43406. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43407. this.onMeshUpdated(mesh);
  43408. };
  43409. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43410. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43411. };
  43412. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43413. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43414. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43415. this.onGeometryUpdated(geometry);
  43416. };
  43417. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43418. this._toRemoveGeometryArray.push(geometry.id);
  43419. };
  43420. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43421. var submeshes = [];
  43422. if (mesh.subMeshes) {
  43423. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43424. var boundingInfo = sm.getBoundingInfo();
  43425. return {
  43426. position: idx,
  43427. verticesStart: sm.verticesStart,
  43428. verticesCount: sm.verticesCount,
  43429. indexStart: sm.indexStart,
  43430. indexCount: sm.indexCount,
  43431. hasMaterial: !!sm.getMaterial(),
  43432. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43433. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43434. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43435. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43436. };
  43437. });
  43438. }
  43439. var geometryId = null;
  43440. if (mesh instanceof BABYLON.Mesh) {
  43441. var geometry = mesh.geometry;
  43442. geometryId = geometry ? geometry.id : null;
  43443. }
  43444. else if (mesh instanceof BABYLON.InstancedMesh) {
  43445. var geometry = mesh.sourceMesh.geometry;
  43446. geometryId = geometry ? geometry.id : null;
  43447. }
  43448. var boundingInfo = mesh.getBoundingInfo();
  43449. return {
  43450. uniqueId: mesh.uniqueId,
  43451. id: mesh.id,
  43452. name: mesh.name,
  43453. geometryId: geometryId,
  43454. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43455. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43456. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43457. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43458. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43459. subMeshes: submeshes,
  43460. checkCollisions: mesh.checkCollisions
  43461. };
  43462. };
  43463. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43464. return {
  43465. id: geometry.id,
  43466. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43467. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43468. indices: new Uint32Array(geometry.getIndices() || []),
  43469. };
  43470. };
  43471. return CollisionCoordinatorWorker;
  43472. }());
  43473. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43474. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43475. function CollisionCoordinatorLegacy() {
  43476. this._scaledPosition = BABYLON.Vector3.Zero();
  43477. this._scaledVelocity = BABYLON.Vector3.Zero();
  43478. this._finalPosition = BABYLON.Vector3.Zero();
  43479. }
  43480. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43481. position.divideToRef(collider.radius, this._scaledPosition);
  43482. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43483. collider.collidedMesh = null;
  43484. collider.retry = 0;
  43485. collider.initialVelocity = this._scaledVelocity;
  43486. collider.initialPosition = this._scaledPosition;
  43487. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43488. this._finalPosition.multiplyInPlace(collider.radius);
  43489. //run the callback
  43490. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43491. };
  43492. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43493. this._scene = scene;
  43494. };
  43495. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43496. //Legacy need no destruction method.
  43497. };
  43498. //No update in legacy mode
  43499. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43500. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43501. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43502. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43503. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43504. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43505. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43506. if (excludedMesh === void 0) { excludedMesh = null; }
  43507. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43508. if (collider.retry >= maximumRetry) {
  43509. finalPosition.copyFrom(position);
  43510. return;
  43511. }
  43512. // Check if this is a mesh else camera or -1
  43513. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43514. collider._initialize(position, velocity, closeDistance);
  43515. // Check all meshes
  43516. for (var index = 0; index < this._scene.meshes.length; index++) {
  43517. var mesh = this._scene.meshes[index];
  43518. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43519. mesh._checkCollision(collider);
  43520. }
  43521. }
  43522. if (!collider.collisionFound) {
  43523. position.addToRef(velocity, finalPosition);
  43524. return;
  43525. }
  43526. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43527. collider._getResponse(position, velocity);
  43528. }
  43529. if (velocity.length() <= closeDistance) {
  43530. finalPosition.copyFrom(position);
  43531. return;
  43532. }
  43533. collider.retry++;
  43534. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43535. };
  43536. return CollisionCoordinatorLegacy;
  43537. }());
  43538. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43539. })(BABYLON || (BABYLON = {}));
  43540. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43541. var BABYLON;
  43542. (function (BABYLON) {
  43543. var Particle = /** @class */ (function () {
  43544. function Particle(particleSystem) {
  43545. this.particleSystem = particleSystem;
  43546. this.position = BABYLON.Vector3.Zero();
  43547. this.direction = BABYLON.Vector3.Zero();
  43548. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43549. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43550. this.lifeTime = 1.0;
  43551. this.age = 0;
  43552. this.size = 0;
  43553. this.angle = 0;
  43554. this.angularSpeed = 0;
  43555. this._currentFrameCounter = 0;
  43556. this.cellIndex = 0;
  43557. if (!this.particleSystem.isAnimationSheetEnabled) {
  43558. return;
  43559. }
  43560. this.cellIndex = this.particleSystem.startSpriteCellID;
  43561. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43562. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43563. }
  43564. else {
  43565. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43566. }
  43567. }
  43568. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43569. // (ageOffset / scaledUpdateSpeed) / available cells
  43570. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43571. this._currentFrameCounter += scaledUpdateSpeed;
  43572. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43573. this._currentFrameCounter = 0;
  43574. this.cellIndex++;
  43575. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43576. this.cellIndex = this.particleSystem.endSpriteCellID;
  43577. }
  43578. }
  43579. };
  43580. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43581. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43582. this.cellIndex++;
  43583. this._currentFrameCounter = 0;
  43584. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43585. if (this.particleSystem.spriteCellLoop) {
  43586. this.cellIndex = this.particleSystem.startSpriteCellID;
  43587. }
  43588. else {
  43589. this.cellIndex = this.particleSystem.endSpriteCellID;
  43590. }
  43591. }
  43592. }
  43593. else {
  43594. this._currentFrameCounter++;
  43595. }
  43596. };
  43597. Particle.prototype.copyTo = function (other) {
  43598. other.position.copyFrom(this.position);
  43599. other.direction.copyFrom(this.direction);
  43600. other.color.copyFrom(this.color);
  43601. other.colorStep.copyFrom(this.colorStep);
  43602. other.lifeTime = this.lifeTime;
  43603. other.age = this.age;
  43604. other.size = this.size;
  43605. other.angle = this.angle;
  43606. other.angularSpeed = this.angularSpeed;
  43607. other.particleSystem = this.particleSystem;
  43608. other.cellIndex = this.cellIndex;
  43609. };
  43610. return Particle;
  43611. }());
  43612. BABYLON.Particle = Particle;
  43613. })(BABYLON || (BABYLON = {}));
  43614. //# sourceMappingURL=babylon.particle.js.map
  43615. var BABYLON;
  43616. (function (BABYLON) {
  43617. var randomNumber = function (min, max) {
  43618. if (min === max) {
  43619. return (min);
  43620. }
  43621. var random = Math.random();
  43622. return ((random * (max - min)) + min);
  43623. };
  43624. var ParticleSystem = /** @class */ (function () {
  43625. // end of sheet animation
  43626. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  43627. if (customEffect === void 0) { customEffect = null; }
  43628. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  43629. if (epsilon === void 0) { epsilon = 0.01; }
  43630. var _this = this;
  43631. this.name = name;
  43632. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  43633. // Members
  43634. this.animations = [];
  43635. this.renderingGroupId = 0;
  43636. this.emitter = null;
  43637. this.emitRate = 10;
  43638. this.manualEmitCount = -1;
  43639. this.updateSpeed = 0.01;
  43640. this.targetStopDuration = 0;
  43641. this.disposeOnStop = false;
  43642. this.minEmitPower = 1;
  43643. this.maxEmitPower = 1;
  43644. this.minLifeTime = 1;
  43645. this.maxLifeTime = 1;
  43646. this.minSize = 1;
  43647. this.maxSize = 1;
  43648. this.minAngularSpeed = 0;
  43649. this.maxAngularSpeed = 0;
  43650. this.layerMask = 0x0FFFFFFF;
  43651. this.customShader = null;
  43652. this.preventAutoStart = false;
  43653. /**
  43654. * An event triggered when the system is disposed.
  43655. * @type {BABYLON.Observable}
  43656. */
  43657. this.onDisposeObservable = new BABYLON.Observable();
  43658. this.onAnimationEnd = null;
  43659. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  43660. this.forceDepthWrite = false;
  43661. this.gravity = BABYLON.Vector3.Zero();
  43662. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  43663. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  43664. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  43665. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43666. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43667. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43668. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  43669. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43670. this.particles = new Array();
  43671. this._stockParticles = new Array();
  43672. this._newPartsExcess = 0;
  43673. this._vertexBuffers = {};
  43674. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  43675. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  43676. this._scaledDirection = BABYLON.Vector3.Zero();
  43677. this._scaledGravity = BABYLON.Vector3.Zero();
  43678. this._currentRenderId = -1;
  43679. this._started = false;
  43680. this._stopped = false;
  43681. this._actualFrame = 0;
  43682. // sheet animation
  43683. this.startSpriteCellID = 0;
  43684. this.endSpriteCellID = 0;
  43685. this.spriteCellLoop = true;
  43686. this.spriteCellChangeSpeed = 0;
  43687. this.spriteCellWidth = 0;
  43688. this.spriteCellHeight = 0;
  43689. this._vertexBufferSize = 11;
  43690. this.appendParticleVertexes = null;
  43691. this.id = name;
  43692. this._capacity = capacity;
  43693. this._epsilon = epsilon;
  43694. if (_isAnimationSheetEnabled) {
  43695. this._vertexBufferSize = 12;
  43696. }
  43697. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43698. this._customEffect = customEffect;
  43699. scene.particleSystems.push(this);
  43700. this._createIndexBuffer();
  43701. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  43702. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  43703. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  43704. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  43705. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  43706. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  43707. if (this._isAnimationSheetEnabled) {
  43708. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  43709. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  43710. }
  43711. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43712. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43713. this._vertexBuffers["options"] = options;
  43714. // Default behaviors
  43715. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  43716. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  43717. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  43718. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  43719. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  43720. };
  43721. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  43722. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  43723. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  43724. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  43725. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  43726. };
  43727. this.updateFunction = function (particles) {
  43728. for (var index = 0; index < particles.length; index++) {
  43729. var particle = particles[index];
  43730. particle.age += _this._scaledUpdateSpeed;
  43731. if (particle.age >= particle.lifeTime) {
  43732. _this.recycleParticle(particle);
  43733. index--;
  43734. continue;
  43735. }
  43736. else {
  43737. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  43738. particle.color.addInPlace(_this._scaledColorStep);
  43739. if (particle.color.a < 0)
  43740. particle.color.a = 0;
  43741. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  43742. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  43743. particle.position.addInPlace(_this._scaledDirection);
  43744. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  43745. particle.direction.addInPlace(_this._scaledGravity);
  43746. if (_this._isAnimationSheetEnabled) {
  43747. particle.updateCellIndex(_this._scaledUpdateSpeed);
  43748. }
  43749. }
  43750. }
  43751. };
  43752. }
  43753. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  43754. set: function (callback) {
  43755. if (this._onDisposeObserver) {
  43756. this.onDisposeObservable.remove(this._onDisposeObserver);
  43757. }
  43758. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43759. },
  43760. enumerable: true,
  43761. configurable: true
  43762. });
  43763. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  43764. get: function () {
  43765. return this._isAnimationSheetEnabled;
  43766. },
  43767. enumerable: true,
  43768. configurable: true
  43769. });
  43770. ParticleSystem.prototype._createIndexBuffer = function () {
  43771. var indices = [];
  43772. var index = 0;
  43773. for (var count = 0; count < this._capacity; count++) {
  43774. indices.push(index);
  43775. indices.push(index + 1);
  43776. indices.push(index + 2);
  43777. indices.push(index);
  43778. indices.push(index + 2);
  43779. indices.push(index + 3);
  43780. index += 4;
  43781. }
  43782. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  43783. };
  43784. ParticleSystem.prototype.recycleParticle = function (particle) {
  43785. var lastParticle = this.particles.pop();
  43786. if (lastParticle !== particle) {
  43787. lastParticle.copyTo(particle);
  43788. this._stockParticles.push(lastParticle);
  43789. }
  43790. };
  43791. ParticleSystem.prototype.getCapacity = function () {
  43792. return this._capacity;
  43793. };
  43794. ParticleSystem.prototype.isAlive = function () {
  43795. return this._alive;
  43796. };
  43797. ParticleSystem.prototype.isStarted = function () {
  43798. return this._started;
  43799. };
  43800. ParticleSystem.prototype.start = function () {
  43801. this._started = true;
  43802. this._stopped = false;
  43803. this._actualFrame = 0;
  43804. };
  43805. ParticleSystem.prototype.stop = function () {
  43806. this._stopped = true;
  43807. };
  43808. // animation sheet
  43809. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  43810. var offset = index * this._vertexBufferSize;
  43811. this._vertexData[offset] = particle.position.x;
  43812. this._vertexData[offset + 1] = particle.position.y;
  43813. this._vertexData[offset + 2] = particle.position.z;
  43814. this._vertexData[offset + 3] = particle.color.r;
  43815. this._vertexData[offset + 4] = particle.color.g;
  43816. this._vertexData[offset + 5] = particle.color.b;
  43817. this._vertexData[offset + 6] = particle.color.a;
  43818. this._vertexData[offset + 7] = particle.angle;
  43819. this._vertexData[offset + 8] = particle.size;
  43820. this._vertexData[offset + 9] = offsetX;
  43821. this._vertexData[offset + 10] = offsetY;
  43822. };
  43823. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  43824. if (offsetX === 0)
  43825. offsetX = this._epsilon;
  43826. else if (offsetX === 1)
  43827. offsetX = 1 - this._epsilon;
  43828. if (offsetY === 0)
  43829. offsetY = this._epsilon;
  43830. else if (offsetY === 1)
  43831. offsetY = 1 - this._epsilon;
  43832. var offset = index * this._vertexBufferSize;
  43833. this._vertexData[offset] = particle.position.x;
  43834. this._vertexData[offset + 1] = particle.position.y;
  43835. this._vertexData[offset + 2] = particle.position.z;
  43836. this._vertexData[offset + 3] = particle.color.r;
  43837. this._vertexData[offset + 4] = particle.color.g;
  43838. this._vertexData[offset + 5] = particle.color.b;
  43839. this._vertexData[offset + 6] = particle.color.a;
  43840. this._vertexData[offset + 7] = particle.angle;
  43841. this._vertexData[offset + 8] = particle.size;
  43842. this._vertexData[offset + 9] = offsetX;
  43843. this._vertexData[offset + 10] = offsetY;
  43844. this._vertexData[offset + 11] = particle.cellIndex;
  43845. };
  43846. ParticleSystem.prototype._update = function (newParticles) {
  43847. // Update current
  43848. this._alive = this.particles.length > 0;
  43849. this.updateFunction(this.particles);
  43850. // Add new ones
  43851. var worldMatrix;
  43852. if (this.emitter.position) {
  43853. var emitterMesh = this.emitter;
  43854. worldMatrix = emitterMesh.getWorldMatrix();
  43855. }
  43856. else {
  43857. var emitterPosition = this.emitter;
  43858. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  43859. }
  43860. var particle;
  43861. for (var index = 0; index < newParticles; index++) {
  43862. if (this.particles.length === this._capacity) {
  43863. break;
  43864. }
  43865. if (this._stockParticles.length !== 0) {
  43866. particle = this._stockParticles.pop();
  43867. particle.age = 0;
  43868. particle.cellIndex = this.startSpriteCellID;
  43869. }
  43870. else {
  43871. particle = new BABYLON.Particle(this);
  43872. }
  43873. this.particles.push(particle);
  43874. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  43875. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  43876. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  43877. particle.size = randomNumber(this.minSize, this.maxSize);
  43878. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  43879. this.startPositionFunction(worldMatrix, particle.position, particle);
  43880. var step = randomNumber(0, 1.0);
  43881. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  43882. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  43883. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  43884. }
  43885. };
  43886. ParticleSystem.prototype._getEffect = function () {
  43887. if (this._customEffect) {
  43888. return this._customEffect;
  43889. }
  43890. ;
  43891. var defines = [];
  43892. if (this._scene.clipPlane) {
  43893. defines.push("#define CLIPPLANE");
  43894. }
  43895. if (this._isAnimationSheetEnabled) {
  43896. defines.push("#define ANIMATESHEET");
  43897. }
  43898. // Effect
  43899. var join = defines.join("\n");
  43900. if (this._cachedDefines !== join) {
  43901. this._cachedDefines = join;
  43902. var attributesNamesOrOptions;
  43903. var effectCreationOption;
  43904. if (this._isAnimationSheetEnabled) {
  43905. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  43906. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  43907. }
  43908. else {
  43909. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  43910. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  43911. }
  43912. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  43913. }
  43914. return this._effect;
  43915. };
  43916. ParticleSystem.prototype.animate = function () {
  43917. if (!this._started)
  43918. return;
  43919. var effect = this._getEffect();
  43920. // Check
  43921. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  43922. return;
  43923. if (this._currentRenderId === this._scene.getRenderId()) {
  43924. return;
  43925. }
  43926. this._currentRenderId = this._scene.getRenderId();
  43927. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  43928. // determine the number of particles we need to create
  43929. var newParticles;
  43930. if (this.manualEmitCount > -1) {
  43931. newParticles = this.manualEmitCount;
  43932. this._newPartsExcess = 0;
  43933. this.manualEmitCount = 0;
  43934. }
  43935. else {
  43936. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  43937. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  43938. }
  43939. if (this._newPartsExcess > 1.0) {
  43940. newParticles += this._newPartsExcess >> 0;
  43941. this._newPartsExcess -= this._newPartsExcess >> 0;
  43942. }
  43943. this._alive = false;
  43944. if (!this._stopped) {
  43945. this._actualFrame += this._scaledUpdateSpeed;
  43946. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  43947. this.stop();
  43948. }
  43949. else {
  43950. newParticles = 0;
  43951. }
  43952. this._update(newParticles);
  43953. // Stopped?
  43954. if (this._stopped) {
  43955. if (!this._alive) {
  43956. this._started = false;
  43957. if (this.onAnimationEnd) {
  43958. this.onAnimationEnd();
  43959. }
  43960. if (this.disposeOnStop) {
  43961. this._scene._toBeDisposed.push(this);
  43962. }
  43963. }
  43964. }
  43965. // Animation sheet
  43966. if (this._isAnimationSheetEnabled) {
  43967. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  43968. }
  43969. else {
  43970. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  43971. }
  43972. // Update VBO
  43973. var offset = 0;
  43974. for (var index = 0; index < this.particles.length; index++) {
  43975. var particle = this.particles[index];
  43976. this.appendParticleVertexes(offset, particle);
  43977. offset += 4;
  43978. }
  43979. if (this._vertexBuffer) {
  43980. this._vertexBuffer.update(this._vertexData);
  43981. }
  43982. };
  43983. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  43984. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  43985. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  43986. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  43987. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  43988. };
  43989. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  43990. this._appendParticleVertex(offset++, particle, 0, 0);
  43991. this._appendParticleVertex(offset++, particle, 1, 0);
  43992. this._appendParticleVertex(offset++, particle, 1, 1);
  43993. this._appendParticleVertex(offset++, particle, 0, 1);
  43994. };
  43995. ParticleSystem.prototype.rebuild = function () {
  43996. this._createIndexBuffer();
  43997. if (this._vertexBuffer) {
  43998. this._vertexBuffer._rebuild();
  43999. }
  44000. };
  44001. ParticleSystem.prototype.render = function () {
  44002. var effect = this._getEffect();
  44003. // Check
  44004. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44005. return 0;
  44006. var engine = this._scene.getEngine();
  44007. // Render
  44008. engine.enableEffect(effect);
  44009. engine.setState(false);
  44010. var viewMatrix = this._scene.getViewMatrix();
  44011. effect.setTexture("diffuseSampler", this.particleTexture);
  44012. effect.setMatrix("view", viewMatrix);
  44013. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44014. if (this._isAnimationSheetEnabled) {
  44015. var baseSize = this.particleTexture.getBaseSize();
  44016. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44017. }
  44018. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44019. if (this._scene.clipPlane) {
  44020. var clipPlane = this._scene.clipPlane;
  44021. var invView = viewMatrix.clone();
  44022. invView.invert();
  44023. effect.setMatrix("invView", invView);
  44024. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44025. }
  44026. // VBOs
  44027. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44028. // Draw order
  44029. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44030. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44031. }
  44032. else {
  44033. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44034. }
  44035. if (this.forceDepthWrite) {
  44036. engine.setDepthWrite(true);
  44037. }
  44038. engine.draw(true, 0, this.particles.length * 6);
  44039. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44040. return this.particles.length;
  44041. };
  44042. ParticleSystem.prototype.dispose = function () {
  44043. if (this._vertexBuffer) {
  44044. this._vertexBuffer.dispose();
  44045. this._vertexBuffer = null;
  44046. }
  44047. if (this._indexBuffer) {
  44048. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44049. this._indexBuffer = null;
  44050. }
  44051. if (this.particleTexture) {
  44052. this.particleTexture.dispose();
  44053. this.particleTexture = null;
  44054. }
  44055. // Remove from scene
  44056. var index = this._scene.particleSystems.indexOf(this);
  44057. if (index > -1) {
  44058. this._scene.particleSystems.splice(index, 1);
  44059. }
  44060. // Callback
  44061. this.onDisposeObservable.notifyObservers(this);
  44062. this.onDisposeObservable.clear();
  44063. };
  44064. // Clone
  44065. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44066. var custom = null;
  44067. var program = null;
  44068. if (this.customShader != null) {
  44069. program = this.customShader;
  44070. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44071. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44072. }
  44073. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44074. result.customShader = program;
  44075. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44076. if (newEmitter === undefined) {
  44077. newEmitter = this.emitter;
  44078. }
  44079. result.emitter = newEmitter;
  44080. if (this.particleTexture) {
  44081. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44082. }
  44083. if (!this.preventAutoStart) {
  44084. result.start();
  44085. }
  44086. return result;
  44087. };
  44088. ParticleSystem.prototype.serialize = function () {
  44089. var serializationObject = {};
  44090. serializationObject.name = this.name;
  44091. serializationObject.id = this.id;
  44092. // Emitter
  44093. if (this.emitter.position) {
  44094. var emitterMesh = this.emitter;
  44095. serializationObject.emitterId = emitterMesh.id;
  44096. }
  44097. else {
  44098. var emitterPosition = this.emitter;
  44099. serializationObject.emitter = emitterPosition.asArray();
  44100. }
  44101. serializationObject.capacity = this.getCapacity();
  44102. if (this.particleTexture) {
  44103. serializationObject.textureName = this.particleTexture.name;
  44104. }
  44105. // Animations
  44106. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44107. // Particle system
  44108. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44109. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44110. serializationObject.minSize = this.minSize;
  44111. serializationObject.maxSize = this.maxSize;
  44112. serializationObject.minEmitPower = this.minEmitPower;
  44113. serializationObject.maxEmitPower = this.maxEmitPower;
  44114. serializationObject.minLifeTime = this.minLifeTime;
  44115. serializationObject.maxLifeTime = this.maxLifeTime;
  44116. serializationObject.emitRate = this.emitRate;
  44117. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44118. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44119. serializationObject.gravity = this.gravity.asArray();
  44120. serializationObject.direction1 = this.direction1.asArray();
  44121. serializationObject.direction2 = this.direction2.asArray();
  44122. serializationObject.color1 = this.color1.asArray();
  44123. serializationObject.color2 = this.color2.asArray();
  44124. serializationObject.colorDead = this.colorDead.asArray();
  44125. serializationObject.updateSpeed = this.updateSpeed;
  44126. serializationObject.targetStopDuration = this.targetStopDuration;
  44127. serializationObject.textureMask = this.textureMask.asArray();
  44128. serializationObject.blendMode = this.blendMode;
  44129. serializationObject.customShader = this.customShader;
  44130. serializationObject.preventAutoStart = this.preventAutoStart;
  44131. return serializationObject;
  44132. };
  44133. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44134. var name = parsedParticleSystem.name;
  44135. var custom = null;
  44136. var program = null;
  44137. if (parsedParticleSystem.customShader) {
  44138. program = parsedParticleSystem.customShader;
  44139. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44140. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44141. }
  44142. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44143. particleSystem.customShader = program;
  44144. if (parsedParticleSystem.id) {
  44145. particleSystem.id = parsedParticleSystem.id;
  44146. }
  44147. // Auto start
  44148. if (parsedParticleSystem.preventAutoStart) {
  44149. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44150. }
  44151. // Texture
  44152. if (parsedParticleSystem.textureName) {
  44153. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44154. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44155. }
  44156. // Emitter
  44157. if (parsedParticleSystem.emitterId) {
  44158. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44159. }
  44160. else {
  44161. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44162. }
  44163. // Animations
  44164. if (parsedParticleSystem.animations) {
  44165. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44166. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44167. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44168. }
  44169. }
  44170. if (parsedParticleSystem.autoAnimate) {
  44171. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44172. }
  44173. // Particle system
  44174. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44175. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44176. particleSystem.minSize = parsedParticleSystem.minSize;
  44177. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44178. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44179. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44180. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44181. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44182. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44183. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44184. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44185. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44186. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44187. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44188. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44189. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44190. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44191. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44192. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44193. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44194. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44195. if (!particleSystem.preventAutoStart) {
  44196. particleSystem.start();
  44197. }
  44198. return particleSystem;
  44199. };
  44200. // Statics
  44201. ParticleSystem.BLENDMODE_ONEONE = 0;
  44202. ParticleSystem.BLENDMODE_STANDARD = 1;
  44203. return ParticleSystem;
  44204. }());
  44205. BABYLON.ParticleSystem = ParticleSystem;
  44206. })(BABYLON || (BABYLON = {}));
  44207. //# sourceMappingURL=babylon.particleSystem.js.map
  44208. var BABYLON;
  44209. (function (BABYLON) {
  44210. var SolidParticle = /** @class */ (function () {
  44211. /**
  44212. * Creates a Solid Particle object.
  44213. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44214. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44215. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44216. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44217. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44218. * `shapeId` (integer) is the model shape identifier in the SPS.
  44219. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44220. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44221. */
  44222. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44223. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44224. this.idx = 0; // particle global index
  44225. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44226. this.position = BABYLON.Vector3.Zero(); // position
  44227. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44228. this.scaling = BABYLON.Vector3.One(); // scaling
  44229. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44230. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44231. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44232. this.alive = true; // alive
  44233. this.isVisible = true; // visibility
  44234. this._pos = 0; // index of this particle in the global "positions" array
  44235. this._ind = 0; // index of this particle in the global "indices" array
  44236. this.shapeId = 0; // model shape id
  44237. this.idxInShape = 0; // index of the particle in its shape id
  44238. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44239. this.idx = particleIndex;
  44240. this._pos = positionIndex;
  44241. this._ind = indiceIndex;
  44242. this._model = model;
  44243. this.shapeId = shapeId;
  44244. this.idxInShape = idxInShape;
  44245. this._sps = sps;
  44246. if (modelBoundingInfo) {
  44247. this._modelBoundingInfo = modelBoundingInfo;
  44248. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44249. }
  44250. }
  44251. Object.defineProperty(SolidParticle.prototype, "scale", {
  44252. /**
  44253. * legacy support, changed scale to scaling
  44254. */
  44255. get: function () {
  44256. return this.scaling;
  44257. },
  44258. set: function (scale) {
  44259. this.scaling = scale;
  44260. },
  44261. enumerable: true,
  44262. configurable: true
  44263. });
  44264. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44265. /**
  44266. * legacy support, changed quaternion to rotationQuaternion
  44267. */
  44268. get: function () {
  44269. return this.rotationQuaternion;
  44270. },
  44271. set: function (q) {
  44272. this.rotationQuaternion = q;
  44273. },
  44274. enumerable: true,
  44275. configurable: true
  44276. });
  44277. /**
  44278. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44279. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44280. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44281. */
  44282. SolidParticle.prototype.intersectsMesh = function (target) {
  44283. if (!this._boundingInfo || !target._boundingInfo) {
  44284. return false;
  44285. }
  44286. if (this._sps._bSphereOnly) {
  44287. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44288. }
  44289. return this._boundingInfo.intersects(target._boundingInfo, false);
  44290. };
  44291. return SolidParticle;
  44292. }());
  44293. BABYLON.SolidParticle = SolidParticle;
  44294. var ModelShape = /** @class */ (function () {
  44295. /**
  44296. * 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.
  44297. * SPS internal tool, don't use it manually.
  44298. */
  44299. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44300. this._indicesLength = 0; // length of the shape in the model indices array
  44301. this.shapeID = id;
  44302. this._shape = shape;
  44303. this._indicesLength = indicesLength;
  44304. this._shapeUV = shapeUV;
  44305. this._positionFunction = posFunction;
  44306. this._vertexFunction = vtxFunction;
  44307. }
  44308. return ModelShape;
  44309. }());
  44310. BABYLON.ModelShape = ModelShape;
  44311. var DepthSortedParticle = /** @class */ (function () {
  44312. function DepthSortedParticle() {
  44313. this.ind = 0; // index of the particle in the "indices" array
  44314. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44315. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44316. }
  44317. return DepthSortedParticle;
  44318. }());
  44319. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44320. })(BABYLON || (BABYLON = {}));
  44321. //# sourceMappingURL=babylon.solidParticle.js.map
  44322. var BABYLON;
  44323. (function (BABYLON) {
  44324. /**
  44325. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44326. */
  44327. var SolidParticleSystem = /** @class */ (function () {
  44328. /**
  44329. * Creates a SPS (Solid Particle System) object.
  44330. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44331. * `scene` (Scene) is the scene in which the SPS is added.
  44332. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44333. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44334. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44335. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44336. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44337. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44338. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44339. */
  44340. function SolidParticleSystem(name, scene, options) {
  44341. // public members
  44342. /**
  44343. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44344. * Example : var p = SPS.particles[i];
  44345. */
  44346. this.particles = new Array();
  44347. /**
  44348. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44349. */
  44350. this.nbParticles = 0;
  44351. /**
  44352. * If the particles must ever face the camera (default false). Useful for planar particles.
  44353. */
  44354. this.billboard = false;
  44355. /**
  44356. * Recompute normals when adding a shape
  44357. */
  44358. this.recomputeNormals = true;
  44359. /**
  44360. * This a counter ofr your own usage. It's not set by any SPS functions.
  44361. */
  44362. this.counter = 0;
  44363. /**
  44364. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44365. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44366. */
  44367. this.vars = {};
  44368. this._positions = new Array();
  44369. this._indices = new Array();
  44370. this._normals = new Array();
  44371. this._colors = new Array();
  44372. this._uvs = new Array();
  44373. this._index = 0; // indices index
  44374. this._updatable = true;
  44375. this._pickable = false;
  44376. this._isVisibilityBoxLocked = false;
  44377. this._alwaysVisible = false;
  44378. this._depthSort = false;
  44379. this._shapeCounter = 0;
  44380. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44381. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44382. this._computeParticleColor = true;
  44383. this._computeParticleTexture = true;
  44384. this._computeParticleRotation = true;
  44385. this._computeParticleVertex = false;
  44386. this._computeBoundingBox = false;
  44387. this._depthSortParticles = true;
  44388. this._cam_axisZ = BABYLON.Vector3.Zero();
  44389. this._cam_axisY = BABYLON.Vector3.Zero();
  44390. this._cam_axisX = BABYLON.Vector3.Zero();
  44391. this._axisZ = BABYLON.Axis.Z;
  44392. this._camDir = BABYLON.Vector3.Zero();
  44393. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44394. this._rotMatrix = new BABYLON.Matrix();
  44395. this._invertMatrix = new BABYLON.Matrix();
  44396. this._rotated = BABYLON.Vector3.Zero();
  44397. this._quaternion = new BABYLON.Quaternion();
  44398. this._vertex = BABYLON.Vector3.Zero();
  44399. this._normal = BABYLON.Vector3.Zero();
  44400. this._yaw = 0.0;
  44401. this._pitch = 0.0;
  44402. this._roll = 0.0;
  44403. this._halfroll = 0.0;
  44404. this._halfpitch = 0.0;
  44405. this._halfyaw = 0.0;
  44406. this._sinRoll = 0.0;
  44407. this._cosRoll = 0.0;
  44408. this._sinPitch = 0.0;
  44409. this._cosPitch = 0.0;
  44410. this._sinYaw = 0.0;
  44411. this._cosYaw = 0.0;
  44412. this._mustUnrotateFixedNormals = false;
  44413. this._minimum = BABYLON.Tmp.Vector3[0];
  44414. this._maximum = BABYLON.Tmp.Vector3[1];
  44415. this._minBbox = BABYLON.Tmp.Vector3[4];
  44416. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44417. this._particlesIntersect = false;
  44418. this._depthSortFunction = function (p1, p2) {
  44419. return (p2.sqDistance - p1.sqDistance);
  44420. };
  44421. this._needs32Bits = false;
  44422. this._bSphereOnly = false;
  44423. this._bSphereRadiusFactor = 1.0;
  44424. this.name = name;
  44425. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44426. this._camera = scene.activeCamera;
  44427. this._pickable = options ? options.isPickable : false;
  44428. this._depthSort = options ? options.enableDepthSort : false;
  44429. this._particlesIntersect = options ? options.particleIntersection : false;
  44430. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44431. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44432. if (options && options.updatable) {
  44433. this._updatable = options.updatable;
  44434. }
  44435. else {
  44436. this._updatable = true;
  44437. }
  44438. if (this._pickable) {
  44439. this.pickedParticles = [];
  44440. }
  44441. if (this._depthSort) {
  44442. this.depthSortedParticles = [];
  44443. }
  44444. }
  44445. /**
  44446. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44447. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44448. */
  44449. SolidParticleSystem.prototype.buildMesh = function () {
  44450. if (this.nbParticles === 0) {
  44451. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44452. this.addShape(triangle, 1);
  44453. triangle.dispose();
  44454. }
  44455. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44456. this._positions32 = new Float32Array(this._positions);
  44457. this._uvs32 = new Float32Array(this._uvs);
  44458. this._colors32 = new Float32Array(this._colors);
  44459. if (this.recomputeNormals) {
  44460. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44461. }
  44462. this._normals32 = new Float32Array(this._normals);
  44463. this._fixedNormal32 = new Float32Array(this._normals);
  44464. if (this._mustUnrotateFixedNormals) {
  44465. this._unrotateFixedNormals();
  44466. }
  44467. var vertexData = new BABYLON.VertexData();
  44468. vertexData.indices = this._indices32;
  44469. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44470. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44471. if (this._uvs32) {
  44472. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44473. ;
  44474. }
  44475. if (this._colors32) {
  44476. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44477. }
  44478. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44479. vertexData.applyToMesh(mesh, this._updatable);
  44480. this.mesh = mesh;
  44481. this.mesh.isPickable = this._pickable;
  44482. // free memory
  44483. if (!this._depthSort) {
  44484. this._indices = null;
  44485. }
  44486. this._positions = null;
  44487. this._normals = null;
  44488. this._uvs = null;
  44489. this._colors = null;
  44490. if (!this._updatable) {
  44491. this.particles.length = 0;
  44492. }
  44493. return mesh;
  44494. };
  44495. /**
  44496. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44497. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44498. * Thus the particles generated from `digest()` have their property `position` set yet.
  44499. * `mesh` ( Mesh ) is the mesh to be digested
  44500. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44501. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44502. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44503. */
  44504. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44505. var size = (options && options.facetNb) || 1;
  44506. var number = (options && options.number) || 0;
  44507. var delta = (options && options.delta) || 0;
  44508. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44509. var meshInd = mesh.getIndices();
  44510. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44511. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44512. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44513. var f = 0; // facet counter
  44514. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44515. // compute size from number
  44516. if (number) {
  44517. number = (number > totalFacets) ? totalFacets : number;
  44518. size = Math.round(totalFacets / number);
  44519. delta = 0;
  44520. }
  44521. else {
  44522. size = (size > totalFacets) ? totalFacets : size;
  44523. }
  44524. var facetPos = []; // submesh positions
  44525. var facetInd = []; // submesh indices
  44526. var facetUV = []; // submesh UV
  44527. var facetCol = []; // submesh colors
  44528. var barycenter = BABYLON.Tmp.Vector3[0];
  44529. var sizeO = size;
  44530. while (f < totalFacets) {
  44531. size = sizeO + Math.floor((1 + delta) * Math.random());
  44532. if (f > totalFacets - size) {
  44533. size = totalFacets - f;
  44534. }
  44535. // reset temp arrays
  44536. facetPos.length = 0;
  44537. facetInd.length = 0;
  44538. facetUV.length = 0;
  44539. facetCol.length = 0;
  44540. // iterate over "size" facets
  44541. var fi = 0;
  44542. for (var j = f * 3; j < (f + size) * 3; j++) {
  44543. facetInd.push(fi);
  44544. var i = meshInd[j];
  44545. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44546. if (meshUV) {
  44547. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44548. }
  44549. if (meshCol) {
  44550. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44551. }
  44552. fi++;
  44553. }
  44554. // create a model shape for each single particle
  44555. var idx = this.nbParticles;
  44556. var shape = this._posToShape(facetPos);
  44557. var shapeUV = this._uvsToShapeUV(facetUV);
  44558. // compute the barycenter of the shape
  44559. var v;
  44560. for (v = 0; v < shape.length; v++) {
  44561. barycenter.addInPlace(shape[v]);
  44562. }
  44563. barycenter.scaleInPlace(1 / shape.length);
  44564. // shift the shape from its barycenter to the origin
  44565. for (v = 0; v < shape.length; v++) {
  44566. shape[v].subtractInPlace(barycenter);
  44567. }
  44568. var bInfo;
  44569. if (this._particlesIntersect) {
  44570. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44571. }
  44572. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44573. // add the particle in the SPS
  44574. var currentPos = this._positions.length;
  44575. var currentInd = this._indices.length;
  44576. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44577. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44578. // initialize the particle position
  44579. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44580. this._index += shape.length;
  44581. idx++;
  44582. this.nbParticles++;
  44583. this._shapeCounter++;
  44584. f += size;
  44585. }
  44586. return this;
  44587. };
  44588. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44589. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44590. var index = 0;
  44591. var idx = 0;
  44592. for (var p = 0; p < this.particles.length; p++) {
  44593. this._particle = this.particles[p];
  44594. this._shape = this._particle._model._shape;
  44595. if (this._particle.rotationQuaternion) {
  44596. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44597. }
  44598. else {
  44599. this._yaw = this._particle.rotation.y;
  44600. this._pitch = this._particle.rotation.x;
  44601. this._roll = this._particle.rotation.z;
  44602. this._quaternionRotationYPR();
  44603. }
  44604. this._quaternionToRotationMatrix();
  44605. this._rotMatrix.invertToRef(this._invertMatrix);
  44606. for (var pt = 0; pt < this._shape.length; pt++) {
  44607. idx = index + pt * 3;
  44608. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44609. this._fixedNormal32[idx] = this._normal.x;
  44610. this._fixedNormal32[idx + 1] = this._normal.y;
  44611. this._fixedNormal32[idx + 2] = this._normal.z;
  44612. }
  44613. index = idx + 3;
  44614. }
  44615. };
  44616. //reset copy
  44617. SolidParticleSystem.prototype._resetCopy = function () {
  44618. this._copy.position.x = 0;
  44619. this._copy.position.y = 0;
  44620. this._copy.position.z = 0;
  44621. this._copy.rotation.x = 0;
  44622. this._copy.rotation.y = 0;
  44623. this._copy.rotation.z = 0;
  44624. this._copy.rotationQuaternion = null;
  44625. this._copy.scaling.x = 1.0;
  44626. this._copy.scaling.y = 1.0;
  44627. this._copy.scaling.z = 1.0;
  44628. this._copy.uvs.x = 0;
  44629. this._copy.uvs.y = 0;
  44630. this._copy.uvs.z = 1.0;
  44631. this._copy.uvs.w = 1.0;
  44632. this._copy.color = null;
  44633. };
  44634. // _meshBuilder : inserts the shape model in the global SPS mesh
  44635. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  44636. var i;
  44637. var u = 0;
  44638. var c = 0;
  44639. var n = 0;
  44640. this._resetCopy();
  44641. if (options && options.positionFunction) {
  44642. options.positionFunction(this._copy, idx, idxInShape);
  44643. this._mustUnrotateFixedNormals = true;
  44644. }
  44645. if (this._copy.rotationQuaternion) {
  44646. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44647. }
  44648. else {
  44649. this._yaw = this._copy.rotation.y;
  44650. this._pitch = this._copy.rotation.x;
  44651. this._roll = this._copy.rotation.z;
  44652. this._quaternionRotationYPR();
  44653. }
  44654. this._quaternionToRotationMatrix();
  44655. for (i = 0; i < shape.length; i++) {
  44656. this._vertex.x = shape[i].x;
  44657. this._vertex.y = shape[i].y;
  44658. this._vertex.z = shape[i].z;
  44659. if (options && options.vertexFunction) {
  44660. options.vertexFunction(this._copy, this._vertex, i);
  44661. }
  44662. this._vertex.x *= this._copy.scaling.x;
  44663. this._vertex.y *= this._copy.scaling.y;
  44664. this._vertex.z *= this._copy.scaling.z;
  44665. this._vertex.x += this._copy.pivot.x;
  44666. this._vertex.y += this._copy.pivot.y;
  44667. this._vertex.z += this._copy.pivot.z;
  44668. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44669. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  44670. if (meshUV) {
  44671. 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);
  44672. u += 2;
  44673. }
  44674. if (this._copy.color) {
  44675. this._color = this._copy.color;
  44676. }
  44677. else if (meshCol && meshCol[c] !== undefined) {
  44678. this._color.r = meshCol[c];
  44679. this._color.g = meshCol[c + 1];
  44680. this._color.b = meshCol[c + 2];
  44681. this._color.a = meshCol[c + 3];
  44682. }
  44683. else {
  44684. this._color.r = 1.0;
  44685. this._color.g = 1.0;
  44686. this._color.b = 1.0;
  44687. this._color.a = 1.0;
  44688. }
  44689. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  44690. c += 4;
  44691. if (!this.recomputeNormals && meshNor) {
  44692. this._normal.x = meshNor[n];
  44693. this._normal.y = meshNor[n + 1];
  44694. this._normal.z = meshNor[n + 2];
  44695. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  44696. normals.push(this._normal.x, this._normal.y, this._normal.z);
  44697. n += 3;
  44698. }
  44699. }
  44700. for (i = 0; i < meshInd.length; i++) {
  44701. var current_ind = p + meshInd[i];
  44702. indices.push(current_ind);
  44703. if (current_ind > 65535) {
  44704. this._needs32Bits = true;
  44705. }
  44706. }
  44707. if (this._pickable) {
  44708. var nbfaces = meshInd.length / 3;
  44709. for (i = 0; i < nbfaces; i++) {
  44710. this.pickedParticles.push({ idx: idx, faceId: i });
  44711. }
  44712. }
  44713. if (this._depthSort) {
  44714. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  44715. }
  44716. return this._copy;
  44717. };
  44718. // returns a shape array from positions array
  44719. SolidParticleSystem.prototype._posToShape = function (positions) {
  44720. var shape = [];
  44721. for (var i = 0; i < positions.length; i += 3) {
  44722. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  44723. }
  44724. return shape;
  44725. };
  44726. // returns a shapeUV array from a Vector4 uvs
  44727. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  44728. var shapeUV = [];
  44729. if (uvs) {
  44730. for (var i = 0; i < uvs.length; i++)
  44731. shapeUV.push(uvs[i]);
  44732. }
  44733. return shapeUV;
  44734. };
  44735. // adds a new particle object in the particles array
  44736. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  44737. if (bInfo === void 0) { bInfo = null; }
  44738. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  44739. this.particles.push(sp);
  44740. return sp;
  44741. };
  44742. /**
  44743. * Adds some particles to the SPS from the model shape. Returns the shape id.
  44744. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  44745. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  44746. * `nb` (positive integer) the number of particles to be created from this model
  44747. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  44748. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  44749. */
  44750. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  44751. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44752. var meshInd = mesh.getIndices();
  44753. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44754. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44755. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44756. var bbInfo;
  44757. if (this._particlesIntersect) {
  44758. bbInfo = mesh.getBoundingInfo();
  44759. }
  44760. var shape = this._posToShape(meshPos);
  44761. var shapeUV = this._uvsToShapeUV(meshUV);
  44762. var posfunc = options ? options.positionFunction : null;
  44763. var vtxfunc = options ? options.vertexFunction : null;
  44764. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  44765. // particles
  44766. var sp;
  44767. var currentCopy;
  44768. var idx = this.nbParticles;
  44769. for (var i = 0; i < nb; i++) {
  44770. var currentPos = this._positions.length;
  44771. var currentInd = this._indices.length;
  44772. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  44773. if (this._updatable) {
  44774. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  44775. sp.position.copyFrom(currentCopy.position);
  44776. sp.rotation.copyFrom(currentCopy.rotation);
  44777. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  44778. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  44779. }
  44780. if (currentCopy.color && sp.color) {
  44781. sp.color.copyFrom(currentCopy.color);
  44782. }
  44783. sp.scaling.copyFrom(currentCopy.scaling);
  44784. sp.uvs.copyFrom(currentCopy.uvs);
  44785. }
  44786. this._index += shape.length;
  44787. idx++;
  44788. }
  44789. this.nbParticles += nb;
  44790. this._shapeCounter++;
  44791. return this._shapeCounter - 1;
  44792. };
  44793. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  44794. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  44795. this._resetCopy();
  44796. if (particle._model._positionFunction) {
  44797. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  44798. }
  44799. if (this._copy.rotationQuaternion) {
  44800. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44801. }
  44802. else {
  44803. this._yaw = this._copy.rotation.y;
  44804. this._pitch = this._copy.rotation.x;
  44805. this._roll = this._copy.rotation.z;
  44806. this._quaternionRotationYPR();
  44807. }
  44808. this._quaternionToRotationMatrix();
  44809. this._shape = particle._model._shape;
  44810. for (var pt = 0; pt < this._shape.length; pt++) {
  44811. this._vertex.x = this._shape[pt].x;
  44812. this._vertex.y = this._shape[pt].y;
  44813. this._vertex.z = this._shape[pt].z;
  44814. if (particle._model._vertexFunction) {
  44815. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  44816. }
  44817. this._vertex.x *= this._copy.scaling.x;
  44818. this._vertex.y *= this._copy.scaling.y;
  44819. this._vertex.z *= this._copy.scaling.z;
  44820. this._vertex.x += this._copy.pivot.x;
  44821. this._vertex.y += this._copy.pivot.y;
  44822. this._vertex.z += this._copy.pivot.z;
  44823. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44824. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  44825. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  44826. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  44827. }
  44828. particle.position.x = 0.0;
  44829. particle.position.y = 0.0;
  44830. particle.position.z = 0.0;
  44831. particle.rotation.x = 0.0;
  44832. particle.rotation.y = 0.0;
  44833. particle.rotation.z = 0.0;
  44834. particle.rotationQuaternion = null;
  44835. particle.scaling.x = 1.0;
  44836. particle.scaling.y = 1.0;
  44837. particle.scaling.z = 1.0;
  44838. };
  44839. /**
  44840. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  44841. * Returns the SPS.
  44842. */
  44843. SolidParticleSystem.prototype.rebuildMesh = function () {
  44844. for (var p = 0; p < this.particles.length; p++) {
  44845. this._rebuildParticle(this.particles[p]);
  44846. }
  44847. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  44848. return this;
  44849. };
  44850. /**
  44851. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  44852. * This method calls `updateParticle()` for each particle of the SPS.
  44853. * For an animated SPS, it is usually called within the render loop.
  44854. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  44855. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  44856. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  44857. * Returns the SPS.
  44858. */
  44859. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  44860. if (start === void 0) { start = 0; }
  44861. if (end === void 0) { end = this.nbParticles - 1; }
  44862. if (update === void 0) { update = true; }
  44863. if (!this._updatable) {
  44864. return this;
  44865. }
  44866. // custom beforeUpdate
  44867. this.beforeUpdateParticles(start, end, update);
  44868. this._cam_axisX.x = 1.0;
  44869. this._cam_axisX.y = 0.0;
  44870. this._cam_axisX.z = 0.0;
  44871. this._cam_axisY.x = 0.0;
  44872. this._cam_axisY.y = 1.0;
  44873. this._cam_axisY.z = 0.0;
  44874. this._cam_axisZ.x = 0.0;
  44875. this._cam_axisZ.y = 0.0;
  44876. this._cam_axisZ.z = 1.0;
  44877. // cases when the World Matrix is to be computed first
  44878. if (this.billboard || this._depthSort) {
  44879. this.mesh.computeWorldMatrix(true);
  44880. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  44881. }
  44882. // if the particles will always face the camera
  44883. if (this.billboard) {
  44884. // compute the camera position and un-rotate it by the current mesh rotation
  44885. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  44886. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  44887. this._cam_axisZ.normalize();
  44888. // same for camera up vector extracted from the cam view matrix
  44889. var view = this._camera.getViewMatrix(true);
  44890. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  44891. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  44892. this._cam_axisY.normalize();
  44893. this._cam_axisX.normalize();
  44894. }
  44895. // if depthSort, compute the camera global position in the mesh local system
  44896. if (this._depthSort) {
  44897. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  44898. }
  44899. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  44900. var idx = 0; // current position index in the global array positions32
  44901. var index = 0; // position start index in the global array positions32 of the current particle
  44902. var colidx = 0; // current color index in the global array colors32
  44903. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  44904. var uvidx = 0; // current uv index in the global array uvs32
  44905. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  44906. var pt = 0; // current index in the particle model shape
  44907. if (this.mesh.isFacetDataEnabled) {
  44908. this._computeBoundingBox = true;
  44909. }
  44910. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  44911. if (this._computeBoundingBox) {
  44912. if (start == 0 && end == this.nbParticles - 1) {
  44913. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  44914. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  44915. }
  44916. else {
  44917. if (this.mesh._boundingInfo) {
  44918. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  44919. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  44920. }
  44921. }
  44922. }
  44923. // particle loop
  44924. index = this.particles[start]._pos;
  44925. var vpos = (index / 3) | 0;
  44926. colorIndex = vpos * 4;
  44927. uvIndex = vpos * 2;
  44928. for (var p = start; p <= end; p++) {
  44929. this._particle = this.particles[p];
  44930. this._shape = this._particle._model._shape;
  44931. this._shapeUV = this._particle._model._shapeUV;
  44932. // call to custom user function to update the particle properties
  44933. this.updateParticle(this._particle);
  44934. // camera-particle distance for depth sorting
  44935. if (this._depthSort && this._depthSortParticles) {
  44936. var dsp = this.depthSortedParticles[p];
  44937. dsp.ind = this._particle._ind;
  44938. dsp.indicesLength = this._particle._model._indicesLength;
  44939. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  44940. }
  44941. // skip the computations for inactive or already invisible particles
  44942. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  44943. // increment indexes for the next particle
  44944. pt = this._shape.length;
  44945. index += pt * 3;
  44946. colorIndex += pt * 4;
  44947. uvIndex += pt * 2;
  44948. continue;
  44949. }
  44950. if (this._particle.isVisible) {
  44951. this._particle._stillInvisible = false; // un-mark permanent invisibility
  44952. // particle rotation matrix
  44953. if (this.billboard) {
  44954. this._particle.rotation.x = 0.0;
  44955. this._particle.rotation.y = 0.0;
  44956. }
  44957. if (this._computeParticleRotation || this.billboard) {
  44958. if (this._particle.rotationQuaternion) {
  44959. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44960. }
  44961. else {
  44962. this._yaw = this._particle.rotation.y;
  44963. this._pitch = this._particle.rotation.x;
  44964. this._roll = this._particle.rotation.z;
  44965. this._quaternionRotationYPR();
  44966. }
  44967. this._quaternionToRotationMatrix();
  44968. }
  44969. // particle vertex loop
  44970. for (pt = 0; pt < this._shape.length; pt++) {
  44971. idx = index + pt * 3;
  44972. colidx = colorIndex + pt * 4;
  44973. uvidx = uvIndex + pt * 2;
  44974. this._vertex.x = this._shape[pt].x;
  44975. this._vertex.y = this._shape[pt].y;
  44976. this._vertex.z = this._shape[pt].z;
  44977. if (this._computeParticleVertex) {
  44978. this.updateParticleVertex(this._particle, this._vertex, pt);
  44979. }
  44980. // positions
  44981. this._vertex.x *= this._particle.scaling.x;
  44982. this._vertex.y *= this._particle.scaling.y;
  44983. this._vertex.z *= this._particle.scaling.z;
  44984. this._vertex.x += this._particle.pivot.x;
  44985. this._vertex.y += this._particle.pivot.y;
  44986. this._vertex.z += this._particle.pivot.z;
  44987. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  44988. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  44989. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  44990. 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;
  44991. 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;
  44992. 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;
  44993. if (this._computeBoundingBox) {
  44994. if (this._positions32[idx] < this._minimum.x) {
  44995. this._minimum.x = this._positions32[idx];
  44996. }
  44997. if (this._positions32[idx] > this._maximum.x) {
  44998. this._maximum.x = this._positions32[idx];
  44999. }
  45000. if (this._positions32[idx + 1] < this._minimum.y) {
  45001. this._minimum.y = this._positions32[idx + 1];
  45002. }
  45003. if (this._positions32[idx + 1] > this._maximum.y) {
  45004. this._maximum.y = this._positions32[idx + 1];
  45005. }
  45006. if (this._positions32[idx + 2] < this._minimum.z) {
  45007. this._minimum.z = this._positions32[idx + 2];
  45008. }
  45009. if (this._positions32[idx + 2] > this._maximum.z) {
  45010. this._maximum.z = this._positions32[idx + 2];
  45011. }
  45012. }
  45013. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45014. if (!this._computeParticleVertex) {
  45015. this._normal.x = this._fixedNormal32[idx];
  45016. this._normal.y = this._fixedNormal32[idx + 1];
  45017. this._normal.z = this._fixedNormal32[idx + 2];
  45018. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45019. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45020. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45021. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45022. 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;
  45023. 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;
  45024. }
  45025. if (this._computeParticleColor && this._particle.color) {
  45026. this._colors32[colidx] = this._particle.color.r;
  45027. this._colors32[colidx + 1] = this._particle.color.g;
  45028. this._colors32[colidx + 2] = this._particle.color.b;
  45029. this._colors32[colidx + 3] = this._particle.color.a;
  45030. }
  45031. if (this._computeParticleTexture) {
  45032. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45033. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45034. }
  45035. }
  45036. }
  45037. else {
  45038. this._particle._stillInvisible = true; // mark the particle as invisible
  45039. for (pt = 0; pt < this._shape.length; pt++) {
  45040. idx = index + pt * 3;
  45041. colidx = colorIndex + pt * 4;
  45042. uvidx = uvIndex + pt * 2;
  45043. this._positions32[idx] = 0.0;
  45044. this._positions32[idx + 1] = 0.0;
  45045. this._positions32[idx + 2] = 0.0;
  45046. this._normals32[idx] = 0.0;
  45047. this._normals32[idx + 1] = 0.0;
  45048. this._normals32[idx + 2] = 0.0;
  45049. if (this._computeParticleColor && this._particle.color) {
  45050. this._colors32[colidx] = this._particle.color.r;
  45051. this._colors32[colidx + 1] = this._particle.color.g;
  45052. this._colors32[colidx + 2] = this._particle.color.b;
  45053. this._colors32[colidx + 3] = this._particle.color.a;
  45054. }
  45055. if (this._computeParticleTexture) {
  45056. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45057. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45058. }
  45059. }
  45060. }
  45061. // if the particle intersections must be computed : update the bbInfo
  45062. if (this._particlesIntersect) {
  45063. var bInfo = this._particle._boundingInfo;
  45064. var bBox = bInfo.boundingBox;
  45065. var bSphere = bInfo.boundingSphere;
  45066. if (!this._bSphereOnly) {
  45067. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45068. for (var b = 0; b < bBox.vectors.length; b++) {
  45069. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45070. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45071. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45072. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45073. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45074. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45075. 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;
  45076. 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;
  45077. 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;
  45078. }
  45079. bBox._update(this.mesh._worldMatrix);
  45080. }
  45081. // place and scale the particle bouding sphere in the SPS local system, then update it
  45082. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45083. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45084. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45085. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45086. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45087. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45088. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45089. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45090. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45091. 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));
  45092. bSphere._update(this.mesh._worldMatrix);
  45093. }
  45094. // increment indexes for the next particle
  45095. index = idx + 3;
  45096. colorIndex = colidx + 4;
  45097. uvIndex = uvidx + 2;
  45098. }
  45099. // if the VBO must be updated
  45100. if (update) {
  45101. if (this._computeParticleColor) {
  45102. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45103. }
  45104. if (this._computeParticleTexture) {
  45105. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45106. }
  45107. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45108. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45109. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45110. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45111. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45112. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45113. for (var i = 0; i < this._normals32.length; i++) {
  45114. this._fixedNormal32[i] = this._normals32[i];
  45115. }
  45116. }
  45117. if (!this.mesh.areNormalsFrozen) {
  45118. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45119. }
  45120. }
  45121. if (this._depthSort && this._depthSortParticles) {
  45122. this.depthSortedParticles.sort(this._depthSortFunction);
  45123. var dspl = this.depthSortedParticles.length;
  45124. var sorted = 0;
  45125. var lind = 0;
  45126. var sind = 0;
  45127. var sid = 0;
  45128. for (sorted = 0; sorted < dspl; sorted++) {
  45129. lind = this.depthSortedParticles[sorted].indicesLength;
  45130. sind = this.depthSortedParticles[sorted].ind;
  45131. for (var i = 0; i < lind; i++) {
  45132. this._indices32[sid] = this._indices[sind + i];
  45133. sid++;
  45134. }
  45135. }
  45136. this.mesh.updateIndices(this._indices32);
  45137. }
  45138. }
  45139. if (this._computeBoundingBox) {
  45140. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45141. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45142. }
  45143. this.afterUpdateParticles(start, end, update);
  45144. return this;
  45145. };
  45146. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45147. this._halfroll = this._roll * 0.5;
  45148. this._halfpitch = this._pitch * 0.5;
  45149. this._halfyaw = this._yaw * 0.5;
  45150. this._sinRoll = Math.sin(this._halfroll);
  45151. this._cosRoll = Math.cos(this._halfroll);
  45152. this._sinPitch = Math.sin(this._halfpitch);
  45153. this._cosPitch = Math.cos(this._halfpitch);
  45154. this._sinYaw = Math.sin(this._halfyaw);
  45155. this._cosYaw = Math.cos(this._halfyaw);
  45156. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45157. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45158. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45159. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45160. };
  45161. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45162. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45163. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45164. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45165. this._rotMatrix.m[3] = 0;
  45166. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45167. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45168. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45169. this._rotMatrix.m[7] = 0;
  45170. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45171. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45172. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45173. this._rotMatrix.m[11] = 0;
  45174. this._rotMatrix.m[12] = 0;
  45175. this._rotMatrix.m[13] = 0;
  45176. this._rotMatrix.m[14] = 0;
  45177. this._rotMatrix.m[15] = 1.0;
  45178. };
  45179. /**
  45180. * Disposes the SPS.
  45181. * Returns nothing.
  45182. */
  45183. SolidParticleSystem.prototype.dispose = function () {
  45184. this.mesh.dispose();
  45185. this.vars = null;
  45186. // drop references to internal big arrays for the GC
  45187. this._positions = null;
  45188. this._indices = null;
  45189. this._normals = null;
  45190. this._uvs = null;
  45191. this._colors = null;
  45192. this._indices32 = null;
  45193. this._positions32 = null;
  45194. this._normals32 = null;
  45195. this._fixedNormal32 = null;
  45196. this._uvs32 = null;
  45197. this._colors32 = null;
  45198. this.pickedParticles = null;
  45199. };
  45200. /**
  45201. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45202. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45203. * Returns the SPS.
  45204. */
  45205. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45206. if (!this._isVisibilityBoxLocked) {
  45207. this.mesh.refreshBoundingInfo();
  45208. }
  45209. return this;
  45210. };
  45211. /**
  45212. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45213. * @param size the size (float) of the visibility box
  45214. * note : this doesn't lock the SPS mesh bounding box.
  45215. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45216. */
  45217. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45218. var vis = size / 2;
  45219. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45220. };
  45221. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45222. // getter and setter
  45223. get: function () {
  45224. return this._alwaysVisible;
  45225. },
  45226. /**
  45227. * Sets the SPS as always visible or not
  45228. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45229. */
  45230. set: function (val) {
  45231. this._alwaysVisible = val;
  45232. this.mesh.alwaysSelectAsActiveMesh = val;
  45233. },
  45234. enumerable: true,
  45235. configurable: true
  45236. });
  45237. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45238. get: function () {
  45239. return this._isVisibilityBoxLocked;
  45240. },
  45241. /**
  45242. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45243. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45244. */
  45245. set: function (val) {
  45246. this._isVisibilityBoxLocked = val;
  45247. var boundingInfo = this.mesh.getBoundingInfo();
  45248. if (boundingInfo) {
  45249. boundingInfo.isLocked = val;
  45250. }
  45251. },
  45252. enumerable: true,
  45253. configurable: true
  45254. });
  45255. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45256. // getters
  45257. get: function () {
  45258. return this._computeParticleRotation;
  45259. },
  45260. // Optimizer setters
  45261. /**
  45262. * Tells to `setParticles()` to compute the particle rotations or not.
  45263. * Default value : true. The SPS is faster when it's set to false.
  45264. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45265. */
  45266. set: function (val) {
  45267. this._computeParticleRotation = val;
  45268. },
  45269. enumerable: true,
  45270. configurable: true
  45271. });
  45272. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45273. get: function () {
  45274. return this._computeParticleColor;
  45275. },
  45276. /**
  45277. * Tells to `setParticles()` to compute the particle colors or not.
  45278. * Default value : true. The SPS is faster when it's set to false.
  45279. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45280. */
  45281. set: function (val) {
  45282. this._computeParticleColor = val;
  45283. },
  45284. enumerable: true,
  45285. configurable: true
  45286. });
  45287. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45288. get: function () {
  45289. return this._computeParticleTexture;
  45290. },
  45291. /**
  45292. * Tells to `setParticles()` to compute the particle textures or not.
  45293. * Default value : true. The SPS is faster when it's set to false.
  45294. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45295. */
  45296. set: function (val) {
  45297. this._computeParticleTexture = val;
  45298. },
  45299. enumerable: true,
  45300. configurable: true
  45301. });
  45302. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45303. get: function () {
  45304. return this._computeParticleVertex;
  45305. },
  45306. /**
  45307. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45308. * Default value : false. The SPS is faster when it's set to false.
  45309. * Note : the particle custom vertex positions aren't stored values.
  45310. */
  45311. set: function (val) {
  45312. this._computeParticleVertex = val;
  45313. },
  45314. enumerable: true,
  45315. configurable: true
  45316. });
  45317. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45318. get: function () {
  45319. return this._computeBoundingBox;
  45320. },
  45321. /**
  45322. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45323. */
  45324. set: function (val) {
  45325. this._computeBoundingBox = val;
  45326. },
  45327. enumerable: true,
  45328. configurable: true
  45329. });
  45330. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45331. get: function () {
  45332. return this._depthSortParticles;
  45333. },
  45334. /**
  45335. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45336. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45337. * Default : `true`
  45338. */
  45339. set: function (val) {
  45340. this._depthSortParticles = val;
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. // =======================================================================
  45346. // Particle behavior logic
  45347. // these following methods may be overwritten by the user to fit his needs
  45348. /**
  45349. * This function does nothing. It may be overwritten to set all the particle first values.
  45350. * The SPS doesn't call this function, you may have to call it by your own.
  45351. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45352. */
  45353. SolidParticleSystem.prototype.initParticles = function () {
  45354. };
  45355. /**
  45356. * This function does nothing. It may be overwritten to recycle a particle.
  45357. * The SPS doesn't call this function, you may have to call it by your own.
  45358. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45359. */
  45360. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45361. return particle;
  45362. };
  45363. /**
  45364. * Updates a particle : this function should be overwritten by the user.
  45365. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45366. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45367. * ex : just set a particle position or velocity and recycle conditions
  45368. */
  45369. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45370. return particle;
  45371. };
  45372. /**
  45373. * Updates a vertex of a particle : it can be overwritten by the user.
  45374. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45375. * @param particle the current particle
  45376. * @param vertex the current index of the current particle
  45377. * @param pt the index of the current vertex in the particle shape
  45378. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45379. * ex : just set a vertex particle position
  45380. */
  45381. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45382. return vertex;
  45383. };
  45384. /**
  45385. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45386. * This does nothing and may be overwritten by the user.
  45387. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45388. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45389. * @param update the boolean update value actually passed to setParticles()
  45390. */
  45391. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45392. };
  45393. /**
  45394. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45395. * This will be passed three parameters.
  45396. * This does nothing and may be overwritten by the user.
  45397. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45398. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45399. * @param update the boolean update value actually passed to setParticles()
  45400. */
  45401. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45402. };
  45403. return SolidParticleSystem;
  45404. }());
  45405. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45406. })(BABYLON || (BABYLON = {}));
  45407. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45408. /// <reference path="babylon.mesh.ts" />
  45409. var BABYLON;
  45410. (function (BABYLON) {
  45411. var GroundMesh = /** @class */ (function (_super) {
  45412. __extends(GroundMesh, _super);
  45413. function GroundMesh(name, scene) {
  45414. var _this = _super.call(this, name, scene) || this;
  45415. _this.generateOctree = false;
  45416. return _this;
  45417. }
  45418. GroundMesh.prototype.getClassName = function () {
  45419. return "GroundMesh";
  45420. };
  45421. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45422. get: function () {
  45423. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45424. },
  45425. enumerable: true,
  45426. configurable: true
  45427. });
  45428. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45429. get: function () {
  45430. return this._subdivisionsX;
  45431. },
  45432. enumerable: true,
  45433. configurable: true
  45434. });
  45435. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45436. get: function () {
  45437. return this._subdivisionsY;
  45438. },
  45439. enumerable: true,
  45440. configurable: true
  45441. });
  45442. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45443. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45444. this._subdivisionsX = chunksCount;
  45445. this._subdivisionsY = chunksCount;
  45446. this.subdivide(chunksCount);
  45447. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45448. };
  45449. /**
  45450. * Returns a height (y) value in the Worl system :
  45451. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45452. * Returns the ground y position if (x, z) are outside the ground surface.
  45453. */
  45454. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45455. var world = this.getWorldMatrix();
  45456. var invMat = BABYLON.Tmp.Matrix[5];
  45457. world.invertToRef(invMat);
  45458. var tmpVect = BABYLON.Tmp.Vector3[8];
  45459. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45460. x = tmpVect.x;
  45461. z = tmpVect.z;
  45462. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45463. return this.position.y;
  45464. }
  45465. if (!this._heightQuads || this._heightQuads.length == 0) {
  45466. this._initHeightQuads();
  45467. this._computeHeightQuads();
  45468. }
  45469. var facet = this._getFacetAt(x, z);
  45470. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45471. // return y in the World system
  45472. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45473. return tmpVect.y;
  45474. };
  45475. /**
  45476. * Returns a normalized vector (Vector3) orthogonal to the ground
  45477. * at the ground coordinates (x, z) expressed in the World system.
  45478. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45479. */
  45480. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45481. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45482. this.getNormalAtCoordinatesToRef(x, z, normal);
  45483. return normal;
  45484. };
  45485. /**
  45486. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45487. * at the ground coordinates (x, z) expressed in the World system.
  45488. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45489. * Returns the GroundMesh.
  45490. */
  45491. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45492. var world = this.getWorldMatrix();
  45493. var tmpMat = BABYLON.Tmp.Matrix[5];
  45494. world.invertToRef(tmpMat);
  45495. var tmpVect = BABYLON.Tmp.Vector3[8];
  45496. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45497. x = tmpVect.x;
  45498. z = tmpVect.z;
  45499. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45500. return this;
  45501. }
  45502. if (!this._heightQuads || this._heightQuads.length == 0) {
  45503. this._initHeightQuads();
  45504. this._computeHeightQuads();
  45505. }
  45506. var facet = this._getFacetAt(x, z);
  45507. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45508. return this;
  45509. };
  45510. /**
  45511. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45512. * if the ground has been updated.
  45513. * This can be used in the render loop.
  45514. * Returns the GroundMesh.
  45515. */
  45516. GroundMesh.prototype.updateCoordinateHeights = function () {
  45517. if (!this._heightQuads || this._heightQuads.length == 0) {
  45518. this._initHeightQuads();
  45519. }
  45520. this._computeHeightQuads();
  45521. return this;
  45522. };
  45523. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45524. GroundMesh.prototype._getFacetAt = function (x, z) {
  45525. // retrieve col and row from x, z coordinates in the ground local system
  45526. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45527. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45528. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45529. var facet;
  45530. if (z < quad.slope.x * x + quad.slope.y) {
  45531. facet = quad.facet1;
  45532. }
  45533. else {
  45534. facet = quad.facet2;
  45535. }
  45536. return facet;
  45537. };
  45538. // Creates and populates the heightMap array with "facet" elements :
  45539. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45540. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45541. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45542. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45543. // Returns the GroundMesh.
  45544. GroundMesh.prototype._initHeightQuads = function () {
  45545. var subdivisionsX = this._subdivisionsX;
  45546. var subdivisionsY = this._subdivisionsY;
  45547. this._heightQuads = new Array();
  45548. for (var row = 0; row < subdivisionsY; row++) {
  45549. for (var col = 0; col < subdivisionsX; col++) {
  45550. 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) };
  45551. this._heightQuads[row * subdivisionsX + col] = quad;
  45552. }
  45553. }
  45554. return this;
  45555. };
  45556. // Compute each quad element values and update the the heightMap array :
  45557. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45558. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45559. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45560. // Returns the GroundMesh.
  45561. GroundMesh.prototype._computeHeightQuads = function () {
  45562. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45563. if (!positions) {
  45564. return this;
  45565. }
  45566. var v1 = BABYLON.Tmp.Vector3[3];
  45567. var v2 = BABYLON.Tmp.Vector3[2];
  45568. var v3 = BABYLON.Tmp.Vector3[1];
  45569. var v4 = BABYLON.Tmp.Vector3[0];
  45570. var v1v2 = BABYLON.Tmp.Vector3[4];
  45571. var v1v3 = BABYLON.Tmp.Vector3[5];
  45572. var v1v4 = BABYLON.Tmp.Vector3[6];
  45573. var norm1 = BABYLON.Tmp.Vector3[7];
  45574. var norm2 = BABYLON.Tmp.Vector3[8];
  45575. var i = 0;
  45576. var j = 0;
  45577. var k = 0;
  45578. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45579. var h = 0;
  45580. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45581. var d2 = 0;
  45582. var subdivisionsX = this._subdivisionsX;
  45583. var subdivisionsY = this._subdivisionsY;
  45584. for (var row = 0; row < subdivisionsY; row++) {
  45585. for (var col = 0; col < subdivisionsX; col++) {
  45586. i = col * 3;
  45587. j = row * (subdivisionsX + 1) * 3;
  45588. k = (row + 1) * (subdivisionsX + 1) * 3;
  45589. v1.x = positions[j + i];
  45590. v1.y = positions[j + i + 1];
  45591. v1.z = positions[j + i + 2];
  45592. v2.x = positions[j + i + 3];
  45593. v2.y = positions[j + i + 4];
  45594. v2.z = positions[j + i + 5];
  45595. v3.x = positions[k + i];
  45596. v3.y = positions[k + i + 1];
  45597. v3.z = positions[k + i + 2];
  45598. v4.x = positions[k + i + 3];
  45599. v4.y = positions[k + i + 4];
  45600. v4.z = positions[k + i + 5];
  45601. // 2D slope V1V4
  45602. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45603. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45604. // facet equations :
  45605. // we compute each facet normal vector
  45606. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45607. // we compute the value d by applying the equation to v1 which belongs to the plane
  45608. // then we store the facet equation in a Vector4
  45609. v2.subtractToRef(v1, v1v2);
  45610. v3.subtractToRef(v1, v1v3);
  45611. v4.subtractToRef(v1, v1v4);
  45612. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45613. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45614. norm1.normalize();
  45615. norm2.normalize();
  45616. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45617. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45618. var quad = this._heightQuads[row * subdivisionsX + col];
  45619. quad.slope.copyFromFloats(cd, h);
  45620. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45621. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45622. }
  45623. }
  45624. return this;
  45625. };
  45626. GroundMesh.prototype.serialize = function (serializationObject) {
  45627. _super.prototype.serialize.call(this, serializationObject);
  45628. serializationObject.subdivisionsX = this._subdivisionsX;
  45629. serializationObject.subdivisionsY = this._subdivisionsY;
  45630. serializationObject.minX = this._minX;
  45631. serializationObject.maxX = this._maxX;
  45632. serializationObject.minZ = this._minZ;
  45633. serializationObject.maxZ = this._maxZ;
  45634. serializationObject.width = this._width;
  45635. serializationObject.height = this._height;
  45636. };
  45637. GroundMesh.Parse = function (parsedMesh, scene) {
  45638. var result = new GroundMesh(parsedMesh.name, scene);
  45639. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  45640. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  45641. result._minX = parsedMesh.minX;
  45642. result._maxX = parsedMesh.maxX;
  45643. result._minZ = parsedMesh.minZ;
  45644. result._maxZ = parsedMesh.maxZ;
  45645. result._width = parsedMesh.width;
  45646. result._height = parsedMesh.height;
  45647. return result;
  45648. };
  45649. return GroundMesh;
  45650. }(BABYLON.Mesh));
  45651. BABYLON.GroundMesh = GroundMesh;
  45652. })(BABYLON || (BABYLON = {}));
  45653. //# sourceMappingURL=babylon.groundMesh.js.map
  45654. var BABYLON;
  45655. (function (BABYLON) {
  45656. /**
  45657. * Creates an instance based on a source mesh.
  45658. */
  45659. var InstancedMesh = /** @class */ (function (_super) {
  45660. __extends(InstancedMesh, _super);
  45661. function InstancedMesh(name, source) {
  45662. var _this = _super.call(this, name, source.getScene()) || this;
  45663. source.instances.push(_this);
  45664. _this._sourceMesh = source;
  45665. _this.position.copyFrom(source.position);
  45666. _this.rotation.copyFrom(source.rotation);
  45667. _this.scaling.copyFrom(source.scaling);
  45668. if (source.rotationQuaternion) {
  45669. _this.rotationQuaternion = source.rotationQuaternion.clone();
  45670. }
  45671. _this.infiniteDistance = source.infiniteDistance;
  45672. _this.setPivotMatrix(source.getPivotMatrix());
  45673. _this.refreshBoundingInfo();
  45674. _this._syncSubMeshes();
  45675. return _this;
  45676. }
  45677. /**
  45678. * Returns the string "InstancedMesh".
  45679. */
  45680. InstancedMesh.prototype.getClassName = function () {
  45681. return "InstancedMesh";
  45682. };
  45683. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  45684. // Methods
  45685. get: function () {
  45686. return this._sourceMesh.receiveShadows;
  45687. },
  45688. enumerable: true,
  45689. configurable: true
  45690. });
  45691. Object.defineProperty(InstancedMesh.prototype, "material", {
  45692. get: function () {
  45693. return this._sourceMesh.material;
  45694. },
  45695. enumerable: true,
  45696. configurable: true
  45697. });
  45698. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  45699. get: function () {
  45700. return this._sourceMesh.visibility;
  45701. },
  45702. enumerable: true,
  45703. configurable: true
  45704. });
  45705. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  45706. get: function () {
  45707. return this._sourceMesh.skeleton;
  45708. },
  45709. enumerable: true,
  45710. configurable: true
  45711. });
  45712. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  45713. get: function () {
  45714. return this._sourceMesh.renderingGroupId;
  45715. },
  45716. enumerable: true,
  45717. configurable: true
  45718. });
  45719. /**
  45720. * Returns the total number of vertices (integer).
  45721. */
  45722. InstancedMesh.prototype.getTotalVertices = function () {
  45723. return this._sourceMesh.getTotalVertices();
  45724. };
  45725. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  45726. get: function () {
  45727. return this._sourceMesh;
  45728. },
  45729. enumerable: true,
  45730. configurable: true
  45731. });
  45732. /**
  45733. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  45734. */
  45735. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  45736. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  45737. };
  45738. /**
  45739. * Sets the vertex data of the mesh geometry for the requested `kind`.
  45740. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  45741. * The `data` are either a numeric array either a Float32Array.
  45742. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  45743. * 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).
  45744. * Note that a new underlying VertexBuffer object is created each call.
  45745. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  45746. *
  45747. * Possible `kind` values :
  45748. * - BABYLON.VertexBuffer.PositionKind
  45749. * - BABYLON.VertexBuffer.UVKind
  45750. * - BABYLON.VertexBuffer.UV2Kind
  45751. * - BABYLON.VertexBuffer.UV3Kind
  45752. * - BABYLON.VertexBuffer.UV4Kind
  45753. * - BABYLON.VertexBuffer.UV5Kind
  45754. * - BABYLON.VertexBuffer.UV6Kind
  45755. * - BABYLON.VertexBuffer.ColorKind
  45756. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45757. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45758. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45759. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45760. *
  45761. * Returns the Mesh.
  45762. */
  45763. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  45764. if (this.sourceMesh) {
  45765. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  45766. }
  45767. return this.sourceMesh;
  45768. };
  45769. /**
  45770. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  45771. * If the mesh has no geometry, it is simply returned as it is.
  45772. * The `data` are either a numeric array either a Float32Array.
  45773. * No new underlying VertexBuffer object is created.
  45774. * 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.
  45775. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  45776. *
  45777. * Possible `kind` values :
  45778. * - BABYLON.VertexBuffer.PositionKind
  45779. * - BABYLON.VertexBuffer.UVKind
  45780. * - BABYLON.VertexBuffer.UV2Kind
  45781. * - BABYLON.VertexBuffer.UV3Kind
  45782. * - BABYLON.VertexBuffer.UV4Kind
  45783. * - BABYLON.VertexBuffer.UV5Kind
  45784. * - BABYLON.VertexBuffer.UV6Kind
  45785. * - BABYLON.VertexBuffer.ColorKind
  45786. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45787. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45788. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45789. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45790. *
  45791. * Returns the Mesh.
  45792. */
  45793. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  45794. if (this.sourceMesh) {
  45795. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  45796. }
  45797. return this.sourceMesh;
  45798. };
  45799. /**
  45800. * Sets the mesh indices.
  45801. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  45802. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  45803. * This method creates a new index buffer each call.
  45804. * Returns the Mesh.
  45805. */
  45806. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  45807. if (totalVertices === void 0) { totalVertices = null; }
  45808. if (this.sourceMesh) {
  45809. this.sourceMesh.setIndices(indices, totalVertices);
  45810. }
  45811. return this.sourceMesh;
  45812. };
  45813. /**
  45814. * Boolean : True if the mesh owns the requested kind of data.
  45815. */
  45816. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  45817. return this._sourceMesh.isVerticesDataPresent(kind);
  45818. };
  45819. /**
  45820. * Returns an array of indices (IndicesArray).
  45821. */
  45822. InstancedMesh.prototype.getIndices = function () {
  45823. return this._sourceMesh.getIndices();
  45824. };
  45825. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  45826. get: function () {
  45827. return this._sourceMesh._positions;
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. /**
  45833. * Sets a new updated BoundingInfo to the mesh.
  45834. * Returns the mesh.
  45835. */
  45836. InstancedMesh.prototype.refreshBoundingInfo = function () {
  45837. var meshBB = this._sourceMesh.getBoundingInfo();
  45838. if (meshBB) {
  45839. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  45840. }
  45841. this._updateBoundingInfo();
  45842. return this;
  45843. };
  45844. InstancedMesh.prototype._preActivate = function () {
  45845. if (this._currentLOD) {
  45846. this._currentLOD._preActivate();
  45847. }
  45848. return this;
  45849. };
  45850. InstancedMesh.prototype._activate = function (renderId) {
  45851. if (this._currentLOD) {
  45852. this._currentLOD._registerInstanceForRenderId(this, renderId);
  45853. }
  45854. return this;
  45855. };
  45856. /**
  45857. * Returns the current associated LOD AbstractMesh.
  45858. */
  45859. InstancedMesh.prototype.getLOD = function (camera) {
  45860. if (!camera) {
  45861. return this;
  45862. }
  45863. var boundingInfo = this.getBoundingInfo();
  45864. if (!boundingInfo) {
  45865. return this;
  45866. }
  45867. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  45868. if (this._currentLOD === this.sourceMesh) {
  45869. return this;
  45870. }
  45871. return this._currentLOD;
  45872. };
  45873. InstancedMesh.prototype._syncSubMeshes = function () {
  45874. this.releaseSubMeshes();
  45875. if (this._sourceMesh.subMeshes) {
  45876. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  45877. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  45878. }
  45879. }
  45880. return this;
  45881. };
  45882. InstancedMesh.prototype._generatePointsArray = function () {
  45883. return this._sourceMesh._generatePointsArray();
  45884. };
  45885. /**
  45886. * Creates a new InstancedMesh from the current mesh.
  45887. * - name (string) : the cloned mesh name
  45888. * - newParent (optional Node) : the optional Node to parent the clone to.
  45889. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  45890. *
  45891. * Returns the clone.
  45892. */
  45893. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  45894. var result = this._sourceMesh.createInstance(name);
  45895. // Deep copy
  45896. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  45897. // Bounding info
  45898. this.refreshBoundingInfo();
  45899. // Parent
  45900. if (newParent) {
  45901. result.parent = newParent;
  45902. }
  45903. if (!doNotCloneChildren) {
  45904. // Children
  45905. for (var index = 0; index < this.getScene().meshes.length; index++) {
  45906. var mesh = this.getScene().meshes[index];
  45907. if (mesh.parent === this) {
  45908. mesh.clone(mesh.name, result);
  45909. }
  45910. }
  45911. }
  45912. result.computeWorldMatrix(true);
  45913. return result;
  45914. };
  45915. /**
  45916. * Disposes the InstancedMesh.
  45917. * Returns nothing.
  45918. */
  45919. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  45920. // Remove from mesh
  45921. var index = this._sourceMesh.instances.indexOf(this);
  45922. this._sourceMesh.instances.splice(index, 1);
  45923. _super.prototype.dispose.call(this, doNotRecurse);
  45924. };
  45925. return InstancedMesh;
  45926. }(BABYLON.AbstractMesh));
  45927. BABYLON.InstancedMesh = InstancedMesh;
  45928. })(BABYLON || (BABYLON = {}));
  45929. //# sourceMappingURL=babylon.instancedMesh.js.map
  45930. /// <reference path="babylon.mesh.ts" />
  45931. var BABYLON;
  45932. (function (BABYLON) {
  45933. var LinesMesh = /** @class */ (function (_super) {
  45934. __extends(LinesMesh, _super);
  45935. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  45936. if (scene === void 0) { scene = null; }
  45937. if (parent === void 0) { parent = null; }
  45938. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  45939. _this.useVertexColor = useVertexColor;
  45940. _this.color = new BABYLON.Color3(1, 1, 1);
  45941. _this.alpha = 1;
  45942. if (source) {
  45943. _this.color = source.color.clone();
  45944. _this.alpha = source.alpha;
  45945. _this.useVertexColor = source.useVertexColor;
  45946. }
  45947. _this._intersectionThreshold = 0.1;
  45948. var options = {
  45949. attributes: [BABYLON.VertexBuffer.PositionKind],
  45950. uniforms: ["world", "viewProjection"],
  45951. needAlphaBlending: false,
  45952. };
  45953. if (!useVertexColor) {
  45954. options.uniforms.push("color");
  45955. options.needAlphaBlending = true;
  45956. }
  45957. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  45958. return _this;
  45959. }
  45960. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  45961. /**
  45962. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  45963. * This margin is expressed in world space coordinates, so its value may vary.
  45964. * Default value is 0.1
  45965. * @returns the intersection Threshold value.
  45966. */
  45967. get: function () {
  45968. return this._intersectionThreshold;
  45969. },
  45970. /**
  45971. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  45972. * This margin is expressed in world space coordinates, so its value may vary.
  45973. * @param value the new threshold to apply
  45974. */
  45975. set: function (value) {
  45976. if (this._intersectionThreshold === value) {
  45977. return;
  45978. }
  45979. this._intersectionThreshold = value;
  45980. if (this.geometry) {
  45981. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  45982. }
  45983. },
  45984. enumerable: true,
  45985. configurable: true
  45986. });
  45987. /**
  45988. * Returns the string "LineMesh"
  45989. */
  45990. LinesMesh.prototype.getClassName = function () {
  45991. return "LinesMesh";
  45992. };
  45993. Object.defineProperty(LinesMesh.prototype, "material", {
  45994. get: function () {
  45995. return this._colorShader;
  45996. },
  45997. enumerable: true,
  45998. configurable: true
  45999. });
  46000. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46001. get: function () {
  46002. return false;
  46003. },
  46004. enumerable: true,
  46005. configurable: true
  46006. });
  46007. LinesMesh.prototype.createInstance = function (name) {
  46008. throw new Error("LinesMeshes do not support createInstance.");
  46009. };
  46010. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46011. if (!this._geometry) {
  46012. return this;
  46013. }
  46014. // VBOs
  46015. this._geometry._bind(this._colorShader.getEffect());
  46016. // Color
  46017. if (!this.useVertexColor) {
  46018. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46019. }
  46020. return this;
  46021. };
  46022. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46023. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46024. return this;
  46025. }
  46026. var engine = this.getScene().getEngine();
  46027. // Draw order
  46028. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46029. return this;
  46030. };
  46031. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46032. this._colorShader.dispose();
  46033. _super.prototype.dispose.call(this, doNotRecurse);
  46034. };
  46035. /**
  46036. * Returns a new LineMesh object cloned from the current one.
  46037. */
  46038. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46039. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46040. };
  46041. return LinesMesh;
  46042. }(BABYLON.Mesh));
  46043. BABYLON.LinesMesh = LinesMesh;
  46044. })(BABYLON || (BABYLON = {}));
  46045. //# sourceMappingURL=babylon.linesMesh.js.map
  46046. var BABYLON;
  46047. (function (BABYLON) {
  46048. var ShaderMaterial = /** @class */ (function (_super) {
  46049. __extends(ShaderMaterial, _super);
  46050. function ShaderMaterial(name, scene, shaderPath, options) {
  46051. var _this = _super.call(this, name, scene) || this;
  46052. _this._textures = {};
  46053. _this._textureArrays = {};
  46054. _this._floats = {};
  46055. _this._floatsArrays = {};
  46056. _this._colors3 = {};
  46057. _this._colors3Arrays = {};
  46058. _this._colors4 = {};
  46059. _this._vectors2 = {};
  46060. _this._vectors3 = {};
  46061. _this._vectors4 = {};
  46062. _this._matrices = {};
  46063. _this._matrices3x3 = {};
  46064. _this._matrices2x2 = {};
  46065. _this._vectors3Arrays = {};
  46066. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46067. _this._shaderPath = shaderPath;
  46068. options.needAlphaBlending = options.needAlphaBlending || false;
  46069. options.needAlphaTesting = options.needAlphaTesting || false;
  46070. options.attributes = options.attributes || ["position", "normal", "uv"];
  46071. options.uniforms = options.uniforms || ["worldViewProjection"];
  46072. options.uniformBuffers = options.uniformBuffers || [];
  46073. options.samplers = options.samplers || [];
  46074. options.defines = options.defines || [];
  46075. _this._options = options;
  46076. return _this;
  46077. }
  46078. ShaderMaterial.prototype.getClassName = function () {
  46079. return "ShaderMaterial";
  46080. };
  46081. ShaderMaterial.prototype.needAlphaBlending = function () {
  46082. return this._options.needAlphaBlending;
  46083. };
  46084. ShaderMaterial.prototype.needAlphaTesting = function () {
  46085. return this._options.needAlphaTesting;
  46086. };
  46087. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46088. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46089. this._options.uniforms.push(uniformName);
  46090. }
  46091. };
  46092. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46093. if (this._options.samplers.indexOf(name) === -1) {
  46094. this._options.samplers.push(name);
  46095. }
  46096. this._textures[name] = texture;
  46097. return this;
  46098. };
  46099. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46100. if (this._options.samplers.indexOf(name) === -1) {
  46101. this._options.samplers.push(name);
  46102. }
  46103. this._checkUniform(name);
  46104. this._textureArrays[name] = textures;
  46105. return this;
  46106. };
  46107. ShaderMaterial.prototype.setFloat = function (name, value) {
  46108. this._checkUniform(name);
  46109. this._floats[name] = value;
  46110. return this;
  46111. };
  46112. ShaderMaterial.prototype.setFloats = function (name, value) {
  46113. this._checkUniform(name);
  46114. this._floatsArrays[name] = value;
  46115. return this;
  46116. };
  46117. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46118. this._checkUniform(name);
  46119. this._colors3[name] = value;
  46120. return this;
  46121. };
  46122. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46123. this._checkUniform(name);
  46124. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46125. color.toArray(arr, arr.length);
  46126. return arr;
  46127. }, []);
  46128. return this;
  46129. };
  46130. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46131. this._checkUniform(name);
  46132. this._colors4[name] = value;
  46133. return this;
  46134. };
  46135. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46136. this._checkUniform(name);
  46137. this._vectors2[name] = value;
  46138. return this;
  46139. };
  46140. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46141. this._checkUniform(name);
  46142. this._vectors3[name] = value;
  46143. return this;
  46144. };
  46145. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46146. this._checkUniform(name);
  46147. this._vectors4[name] = value;
  46148. return this;
  46149. };
  46150. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46151. this._checkUniform(name);
  46152. this._matrices[name] = value;
  46153. return this;
  46154. };
  46155. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46156. this._checkUniform(name);
  46157. this._matrices3x3[name] = value;
  46158. return this;
  46159. };
  46160. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46161. this._checkUniform(name);
  46162. this._matrices2x2[name] = value;
  46163. return this;
  46164. };
  46165. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46166. this._checkUniform(name);
  46167. this._vectors3Arrays[name] = value;
  46168. return this;
  46169. };
  46170. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46171. if (!mesh) {
  46172. return true;
  46173. }
  46174. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46175. return false;
  46176. }
  46177. return false;
  46178. };
  46179. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46180. var scene = this.getScene();
  46181. var engine = scene.getEngine();
  46182. if (!this.checkReadyOnEveryCall) {
  46183. if (this._renderId === scene.getRenderId()) {
  46184. if (this._checkCache(scene, mesh, useInstances)) {
  46185. return true;
  46186. }
  46187. }
  46188. }
  46189. // Instances
  46190. var defines = [];
  46191. var attribs = [];
  46192. var fallbacks = new BABYLON.EffectFallbacks();
  46193. if (useInstances) {
  46194. defines.push("#define INSTANCES");
  46195. }
  46196. for (var index = 0; index < this._options.defines.length; index++) {
  46197. defines.push(this._options.defines[index]);
  46198. }
  46199. for (var index = 0; index < this._options.attributes.length; index++) {
  46200. attribs.push(this._options.attributes[index]);
  46201. }
  46202. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46203. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46204. defines.push("#define VERTEXCOLOR");
  46205. }
  46206. // Bones
  46207. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46208. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46209. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46210. if (mesh.numBoneInfluencers > 4) {
  46211. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46212. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46213. }
  46214. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46215. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46216. fallbacks.addCPUSkinningFallback(0, mesh);
  46217. if (this._options.uniforms.indexOf("mBones") === -1) {
  46218. this._options.uniforms.push("mBones");
  46219. }
  46220. }
  46221. else {
  46222. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46223. }
  46224. // Textures
  46225. for (var name in this._textures) {
  46226. if (!this._textures[name].isReady()) {
  46227. return false;
  46228. }
  46229. }
  46230. // Alpha test
  46231. if (engine.getAlphaTesting()) {
  46232. defines.push("#define ALPHATEST");
  46233. }
  46234. var previousEffect = this._effect;
  46235. var join = defines.join("\n");
  46236. this._effect = engine.createEffect(this._shaderPath, {
  46237. attributes: attribs,
  46238. uniformsNames: this._options.uniforms,
  46239. uniformBuffersNames: this._options.uniformBuffers,
  46240. samplers: this._options.samplers,
  46241. defines: join,
  46242. fallbacks: fallbacks,
  46243. onCompiled: this.onCompiled,
  46244. onError: this.onError
  46245. }, engine);
  46246. if (!this._effect.isReady()) {
  46247. return false;
  46248. }
  46249. if (previousEffect !== this._effect) {
  46250. scene.resetCachedMaterial();
  46251. }
  46252. this._renderId = scene.getRenderId();
  46253. return true;
  46254. };
  46255. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46256. var scene = this.getScene();
  46257. if (!this._effect) {
  46258. return;
  46259. }
  46260. if (this._options.uniforms.indexOf("world") !== -1) {
  46261. this._effect.setMatrix("world", world);
  46262. }
  46263. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46264. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46265. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46266. }
  46267. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46268. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46269. }
  46270. };
  46271. ShaderMaterial.prototype.bind = function (world, mesh) {
  46272. // Std values
  46273. this.bindOnlyWorldMatrix(world);
  46274. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46275. if (this._options.uniforms.indexOf("view") !== -1) {
  46276. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46277. }
  46278. if (this._options.uniforms.indexOf("projection") !== -1) {
  46279. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46280. }
  46281. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46282. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46283. }
  46284. // Bones
  46285. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46286. var name;
  46287. // Texture
  46288. for (name in this._textures) {
  46289. this._effect.setTexture(name, this._textures[name]);
  46290. }
  46291. // Texture arrays
  46292. for (name in this._textureArrays) {
  46293. this._effect.setTextureArray(name, this._textureArrays[name]);
  46294. }
  46295. // Float
  46296. for (name in this._floats) {
  46297. this._effect.setFloat(name, this._floats[name]);
  46298. }
  46299. // Float s
  46300. for (name in this._floatsArrays) {
  46301. this._effect.setArray(name, this._floatsArrays[name]);
  46302. }
  46303. // Color3
  46304. for (name in this._colors3) {
  46305. this._effect.setColor3(name, this._colors3[name]);
  46306. }
  46307. for (name in this._colors3Arrays) {
  46308. this._effect.setArray3(name, this._colors3Arrays[name]);
  46309. }
  46310. // Color4
  46311. for (name in this._colors4) {
  46312. var color = this._colors4[name];
  46313. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46314. }
  46315. // Vector2
  46316. for (name in this._vectors2) {
  46317. this._effect.setVector2(name, this._vectors2[name]);
  46318. }
  46319. // Vector3
  46320. for (name in this._vectors3) {
  46321. this._effect.setVector3(name, this._vectors3[name]);
  46322. }
  46323. // Vector4
  46324. for (name in this._vectors4) {
  46325. this._effect.setVector4(name, this._vectors4[name]);
  46326. }
  46327. // Matrix
  46328. for (name in this._matrices) {
  46329. this._effect.setMatrix(name, this._matrices[name]);
  46330. }
  46331. // Matrix 3x3
  46332. for (name in this._matrices3x3) {
  46333. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46334. }
  46335. // Matrix 2x2
  46336. for (name in this._matrices2x2) {
  46337. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46338. }
  46339. // Vector3Array
  46340. for (name in this._vectors3Arrays) {
  46341. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46342. }
  46343. }
  46344. this._afterBind(mesh);
  46345. };
  46346. ShaderMaterial.prototype.getActiveTextures = function () {
  46347. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46348. for (var name in this._textures) {
  46349. activeTextures.push(this._textures[name]);
  46350. }
  46351. for (var name in this._textureArrays) {
  46352. var array = this._textureArrays[name];
  46353. for (var index = 0; index < array.length; index++) {
  46354. activeTextures.push(array[index]);
  46355. }
  46356. }
  46357. return activeTextures;
  46358. };
  46359. ShaderMaterial.prototype.hasTexture = function (texture) {
  46360. if (_super.prototype.hasTexture.call(this, texture)) {
  46361. return true;
  46362. }
  46363. for (var name in this._textures) {
  46364. if (this._textures[name] === texture) {
  46365. return true;
  46366. }
  46367. }
  46368. for (var name in this._textureArrays) {
  46369. var array = this._textureArrays[name];
  46370. for (var index = 0; index < array.length; index++) {
  46371. if (array[index] === texture) {
  46372. return true;
  46373. }
  46374. }
  46375. }
  46376. return false;
  46377. };
  46378. ShaderMaterial.prototype.clone = function (name) {
  46379. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46380. return newShaderMaterial;
  46381. };
  46382. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46383. if (forceDisposeTextures) {
  46384. var name;
  46385. for (name in this._textures) {
  46386. this._textures[name].dispose();
  46387. }
  46388. for (name in this._textureArrays) {
  46389. var array = this._textureArrays[name];
  46390. for (var index = 0; index < array.length; index++) {
  46391. array[index].dispose();
  46392. }
  46393. }
  46394. }
  46395. this._textures = {};
  46396. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46397. };
  46398. ShaderMaterial.prototype.serialize = function () {
  46399. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46400. serializationObject.customType = "BABYLON.ShaderMaterial";
  46401. serializationObject.options = this._options;
  46402. serializationObject.shaderPath = this._shaderPath;
  46403. var name;
  46404. // Texture
  46405. serializationObject.textures = {};
  46406. for (name in this._textures) {
  46407. serializationObject.textures[name] = this._textures[name].serialize();
  46408. }
  46409. // Texture arrays
  46410. serializationObject.textureArrays = {};
  46411. for (name in this._textureArrays) {
  46412. serializationObject.textureArrays[name] = [];
  46413. var array = this._textureArrays[name];
  46414. for (var index = 0; index < array.length; index++) {
  46415. serializationObject.textureArrays[name].push(array[index].serialize());
  46416. }
  46417. }
  46418. // Float
  46419. serializationObject.floats = {};
  46420. for (name in this._floats) {
  46421. serializationObject.floats[name] = this._floats[name];
  46422. }
  46423. // Float s
  46424. serializationObject.FloatArrays = {};
  46425. for (name in this._floatsArrays) {
  46426. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46427. }
  46428. // Color3
  46429. serializationObject.colors3 = {};
  46430. for (name in this._colors3) {
  46431. serializationObject.colors3[name] = this._colors3[name].asArray();
  46432. }
  46433. // Color3 array
  46434. serializationObject.colors3Arrays = {};
  46435. for (name in this._colors3Arrays) {
  46436. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46437. }
  46438. // Color4
  46439. serializationObject.colors4 = {};
  46440. for (name in this._colors4) {
  46441. serializationObject.colors4[name] = this._colors4[name].asArray();
  46442. }
  46443. // Vector2
  46444. serializationObject.vectors2 = {};
  46445. for (name in this._vectors2) {
  46446. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46447. }
  46448. // Vector3
  46449. serializationObject.vectors3 = {};
  46450. for (name in this._vectors3) {
  46451. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46452. }
  46453. // Vector4
  46454. serializationObject.vectors4 = {};
  46455. for (name in this._vectors4) {
  46456. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46457. }
  46458. // Matrix
  46459. serializationObject.matrices = {};
  46460. for (name in this._matrices) {
  46461. serializationObject.matrices[name] = this._matrices[name].asArray();
  46462. }
  46463. // Matrix 3x3
  46464. serializationObject.matrices3x3 = {};
  46465. for (name in this._matrices3x3) {
  46466. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46467. }
  46468. // Matrix 2x2
  46469. serializationObject.matrices2x2 = {};
  46470. for (name in this._matrices2x2) {
  46471. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46472. }
  46473. // Vector3Array
  46474. serializationObject.vectors3Arrays = {};
  46475. for (name in this._vectors3Arrays) {
  46476. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46477. }
  46478. return serializationObject;
  46479. };
  46480. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46481. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46482. var name;
  46483. // Texture
  46484. for (name in source.textures) {
  46485. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46486. }
  46487. // Texture arrays
  46488. for (name in source.textureArrays) {
  46489. var array = source.textureArrays[name];
  46490. var textureArray = new Array();
  46491. for (var index = 0; index < array.length; index++) {
  46492. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46493. }
  46494. material.setTextureArray(name, textureArray);
  46495. }
  46496. // Float
  46497. for (name in source.floats) {
  46498. material.setFloat(name, source.floats[name]);
  46499. }
  46500. // Float s
  46501. for (name in source.floatsArrays) {
  46502. material.setFloats(name, source.floatsArrays[name]);
  46503. }
  46504. // Color3
  46505. for (name in source.colors3) {
  46506. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46507. }
  46508. // Color3 arrays
  46509. for (name in source.colors3Arrays) {
  46510. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46511. if (i % 3 === 0) {
  46512. arr.push([num]);
  46513. }
  46514. else {
  46515. arr[arr.length - 1].push(num);
  46516. }
  46517. return arr;
  46518. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46519. material.setColor3Array(name, colors);
  46520. }
  46521. // Color4
  46522. for (name in source.colors4) {
  46523. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46524. }
  46525. // Vector2
  46526. for (name in source.vectors2) {
  46527. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46528. }
  46529. // Vector3
  46530. for (name in source.vectors3) {
  46531. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46532. }
  46533. // Vector4
  46534. for (name in source.vectors4) {
  46535. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46536. }
  46537. // Matrix
  46538. for (name in source.matrices) {
  46539. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46540. }
  46541. // Matrix 3x3
  46542. for (name in source.matrices3x3) {
  46543. material.setMatrix3x3(name, source.matrices3x3[name]);
  46544. }
  46545. // Matrix 2x2
  46546. for (name in source.matrices2x2) {
  46547. material.setMatrix2x2(name, source.matrices2x2[name]);
  46548. }
  46549. // Vector3Array
  46550. for (name in source.vectors3Arrays) {
  46551. material.setArray3(name, source.vectors3Arrays[name]);
  46552. }
  46553. return material;
  46554. };
  46555. return ShaderMaterial;
  46556. }(BABYLON.Material));
  46557. BABYLON.ShaderMaterial = ShaderMaterial;
  46558. })(BABYLON || (BABYLON = {}));
  46559. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46560. var BABYLON;
  46561. (function (BABYLON) {
  46562. var MeshBuilder = /** @class */ (function () {
  46563. function MeshBuilder() {
  46564. }
  46565. MeshBuilder.updateSideOrientation = function (orientation) {
  46566. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46567. return BABYLON.Mesh.DOUBLESIDE;
  46568. }
  46569. if (orientation === undefined || orientation === null) {
  46570. return BABYLON.Mesh.FRONTSIDE;
  46571. }
  46572. return orientation;
  46573. };
  46574. /**
  46575. * Creates a box mesh.
  46576. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46577. * The parameter `size` sets the size (float) of each box side (default 1).
  46578. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46579. * 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).
  46580. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46581. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46582. * 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).
  46583. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46585. */
  46586. MeshBuilder.CreateBox = function (name, options, scene) {
  46587. if (scene === void 0) { scene = null; }
  46588. var box = new BABYLON.Mesh(name, scene);
  46589. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46590. box._originalBuilderSideOrientation = options.sideOrientation;
  46591. var vertexData = BABYLON.VertexData.CreateBox(options);
  46592. vertexData.applyToMesh(box, options.updatable);
  46593. return box;
  46594. };
  46595. /**
  46596. * Creates a sphere mesh.
  46597. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46598. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46599. * 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`).
  46600. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46601. * 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
  46602. * 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).
  46603. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46604. * 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).
  46605. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46606. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46607. */
  46608. MeshBuilder.CreateSphere = function (name, options, scene) {
  46609. var sphere = new BABYLON.Mesh(name, scene);
  46610. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46611. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46612. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46613. vertexData.applyToMesh(sphere, options.updatable);
  46614. return sphere;
  46615. };
  46616. /**
  46617. * Creates a plane polygonal mesh. By default, this is a disc.
  46618. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46619. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46620. * 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.
  46621. * 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
  46622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46623. * 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).
  46624. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46626. */
  46627. MeshBuilder.CreateDisc = function (name, options, scene) {
  46628. if (scene === void 0) { scene = null; }
  46629. var disc = new BABYLON.Mesh(name, scene);
  46630. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46631. disc._originalBuilderSideOrientation = options.sideOrientation;
  46632. var vertexData = BABYLON.VertexData.CreateDisc(options);
  46633. vertexData.applyToMesh(disc, options.updatable);
  46634. return disc;
  46635. };
  46636. /**
  46637. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  46638. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  46639. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  46640. * 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`).
  46641. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  46642. * 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.
  46643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46644. * 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).
  46645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46647. */
  46648. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  46649. var sphere = new BABYLON.Mesh(name, scene);
  46650. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46651. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46652. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  46653. vertexData.applyToMesh(sphere, options.updatable);
  46654. return sphere;
  46655. };
  46656. ;
  46657. /**
  46658. * Creates a ribbon mesh.
  46659. * 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.
  46660. *
  46661. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  46662. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  46663. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  46664. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  46665. * 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.
  46666. * 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.
  46667. * 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
  46668. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46669. * 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).
  46670. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46671. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46672. * 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.
  46673. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  46674. * 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
  46675. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  46676. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  46677. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46678. */
  46679. MeshBuilder.CreateRibbon = function (name, options, scene) {
  46680. if (scene === void 0) { scene = null; }
  46681. var pathArray = options.pathArray;
  46682. var closeArray = options.closeArray;
  46683. var closePath = options.closePath;
  46684. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46685. var instance = options.instance;
  46686. var updatable = options.updatable;
  46687. if (instance) {
  46688. // positionFunction : ribbon case
  46689. // only pathArray and sideOrientation parameters are taken into account for positions update
  46690. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  46691. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  46692. var positionFunction = function (positions) {
  46693. var minlg = pathArray[0].length;
  46694. var i = 0;
  46695. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  46696. for (var si = 1; si <= ns; si++) {
  46697. for (var p = 0; p < pathArray.length; p++) {
  46698. var path = pathArray[p];
  46699. var l = path.length;
  46700. minlg = (minlg < l) ? minlg : l;
  46701. var j = 0;
  46702. while (j < minlg) {
  46703. positions[i] = path[j].x;
  46704. positions[i + 1] = path[j].y;
  46705. positions[i + 2] = path[j].z;
  46706. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  46707. BABYLON.Tmp.Vector3[0].x = path[j].x;
  46708. }
  46709. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  46710. BABYLON.Tmp.Vector3[1].x = path[j].x;
  46711. }
  46712. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  46713. BABYLON.Tmp.Vector3[0].y = path[j].y;
  46714. }
  46715. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  46716. BABYLON.Tmp.Vector3[1].y = path[j].y;
  46717. }
  46718. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  46719. BABYLON.Tmp.Vector3[0].z = path[j].z;
  46720. }
  46721. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  46722. BABYLON.Tmp.Vector3[1].z = path[j].z;
  46723. }
  46724. j++;
  46725. i += 3;
  46726. }
  46727. if (instance._closePath) {
  46728. positions[i] = path[0].x;
  46729. positions[i + 1] = path[0].y;
  46730. positions[i + 2] = path[0].z;
  46731. i += 3;
  46732. }
  46733. }
  46734. }
  46735. };
  46736. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46737. positionFunction(positions);
  46738. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  46739. instance._boundingInfo.update(instance._worldMatrix);
  46740. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  46741. if (options.colors) {
  46742. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46743. for (var c = 0; c < options.colors.length; c++) {
  46744. colors[c * 4] = options.colors[c].r;
  46745. colors[c * 4 + 1] = options.colors[c].g;
  46746. colors[c * 4 + 2] = options.colors[c].b;
  46747. colors[c * 4 + 3] = options.colors[c].a;
  46748. }
  46749. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  46750. }
  46751. if (options.uvs) {
  46752. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46753. for (var i = 0; i < options.uvs.length; i++) {
  46754. uvs[i * 2] = options.uvs[i].x;
  46755. uvs[i * 2 + 1] = options.uvs[i].y;
  46756. }
  46757. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  46758. }
  46759. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  46760. var indices = instance.getIndices();
  46761. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46762. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  46763. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  46764. if (instance._closePath) {
  46765. var indexFirst = 0;
  46766. var indexLast = 0;
  46767. for (var p = 0; p < pathArray.length; p++) {
  46768. indexFirst = instance._idx[p] * 3;
  46769. if (p + 1 < pathArray.length) {
  46770. indexLast = (instance._idx[p + 1] - 1) * 3;
  46771. }
  46772. else {
  46773. indexLast = normals.length - 3;
  46774. }
  46775. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  46776. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  46777. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  46778. normals[indexLast] = normals[indexFirst];
  46779. normals[indexLast + 1] = normals[indexFirst + 1];
  46780. normals[indexLast + 2] = normals[indexFirst + 2];
  46781. }
  46782. }
  46783. if (!(instance.areNormalsFrozen)) {
  46784. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  46785. }
  46786. }
  46787. return instance;
  46788. }
  46789. else {
  46790. var ribbon = new BABYLON.Mesh(name, scene);
  46791. ribbon._originalBuilderSideOrientation = sideOrientation;
  46792. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  46793. if (closePath) {
  46794. ribbon._idx = vertexData._idx;
  46795. }
  46796. ribbon._closePath = closePath;
  46797. ribbon._closeArray = closeArray;
  46798. vertexData.applyToMesh(ribbon, updatable);
  46799. return ribbon;
  46800. }
  46801. };
  46802. /**
  46803. * Creates a cylinder or a cone mesh.
  46804. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  46805. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  46806. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  46807. * 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.
  46808. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  46809. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  46810. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  46811. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  46812. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  46813. * 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).
  46814. * 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
  46815. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  46816. * 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
  46817. * 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.
  46818. * If `enclose` is false, a ring surface is one element.
  46819. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  46820. * 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
  46821. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46822. * 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).
  46823. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46825. */
  46826. MeshBuilder.CreateCylinder = function (name, options, scene) {
  46827. var cylinder = new BABYLON.Mesh(name, scene);
  46828. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46829. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  46830. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  46831. vertexData.applyToMesh(cylinder, options.updatable);
  46832. return cylinder;
  46833. };
  46834. /**
  46835. * Creates a torus mesh.
  46836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  46837. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  46838. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  46839. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  46840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46841. * 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).
  46842. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46844. */
  46845. MeshBuilder.CreateTorus = function (name, options, scene) {
  46846. var torus = new BABYLON.Mesh(name, scene);
  46847. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46848. torus._originalBuilderSideOrientation = options.sideOrientation;
  46849. var vertexData = BABYLON.VertexData.CreateTorus(options);
  46850. vertexData.applyToMesh(torus, options.updatable);
  46851. return torus;
  46852. };
  46853. /**
  46854. * Creates a torus knot mesh.
  46855. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  46856. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  46857. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  46858. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  46859. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  46860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46861. * 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).
  46862. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46864. */
  46865. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  46866. var torusKnot = new BABYLON.Mesh(name, scene);
  46867. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46868. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  46869. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  46870. vertexData.applyToMesh(torusKnot, options.updatable);
  46871. return torusKnot;
  46872. };
  46873. /**
  46874. * Creates a line system mesh.
  46875. * A line system is a pool of many lines gathered in a single mesh.
  46876. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  46877. * 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.
  46878. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  46879. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  46880. * 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
  46881. * 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
  46882. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  46883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46884. */
  46885. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  46886. var instance = options.instance;
  46887. var lines = options.lines;
  46888. if (instance) {
  46889. var positionFunction = function (positions) {
  46890. var i = 0;
  46891. for (var l = 0; l < lines.length; l++) {
  46892. var points = lines[l];
  46893. for (var p = 0; p < points.length; p++) {
  46894. positions[i] = points[p].x;
  46895. positions[i + 1] = points[p].y;
  46896. positions[i + 2] = points[p].z;
  46897. i += 3;
  46898. }
  46899. }
  46900. };
  46901. instance.updateMeshPositions(positionFunction, false);
  46902. return instance;
  46903. }
  46904. // line system creation
  46905. var lineSystem = new BABYLON.LinesMesh(name, scene);
  46906. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  46907. vertexData.applyToMesh(lineSystem, options.updatable);
  46908. return lineSystem;
  46909. };
  46910. /**
  46911. * Creates a line mesh.
  46912. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  46913. * 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.
  46914. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  46915. * The parameter `points` is an array successive Vector3.
  46916. * 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
  46917. * When updating an instance, remember that only point positions can change, not the number of points.
  46918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46919. */
  46920. MeshBuilder.CreateLines = function (name, options, scene) {
  46921. if (scene === void 0) { scene = null; }
  46922. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  46923. return lines;
  46924. };
  46925. /**
  46926. * Creates a dashed line mesh.
  46927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  46928. * 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.
  46929. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  46930. * The parameter `points` is an array successive Vector3.
  46931. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  46932. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  46933. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  46934. * 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
  46935. * When updating an instance, remember that only point positions can change, not the number of points.
  46936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46937. */
  46938. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  46939. if (scene === void 0) { scene = null; }
  46940. var points = options.points;
  46941. var instance = options.instance;
  46942. var gapSize = options.gapSize || 1;
  46943. var dashSize = options.dashSize || 3;
  46944. if (instance) {
  46945. var positionFunction = function (positions) {
  46946. var curvect = BABYLON.Vector3.Zero();
  46947. var nbSeg = positions.length / 6;
  46948. var lg = 0;
  46949. var nb = 0;
  46950. var shft = 0;
  46951. var dashshft = 0;
  46952. var curshft = 0;
  46953. var p = 0;
  46954. var i = 0;
  46955. var j = 0;
  46956. for (i = 0; i < points.length - 1; i++) {
  46957. points[i + 1].subtractToRef(points[i], curvect);
  46958. lg += curvect.length();
  46959. }
  46960. shft = lg / nbSeg;
  46961. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  46962. for (i = 0; i < points.length - 1; i++) {
  46963. points[i + 1].subtractToRef(points[i], curvect);
  46964. nb = Math.floor(curvect.length() / shft);
  46965. curvect.normalize();
  46966. j = 0;
  46967. while (j < nb && p < positions.length) {
  46968. curshft = shft * j;
  46969. positions[p] = points[i].x + curshft * curvect.x;
  46970. positions[p + 1] = points[i].y + curshft * curvect.y;
  46971. positions[p + 2] = points[i].z + curshft * curvect.z;
  46972. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  46973. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  46974. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  46975. p += 6;
  46976. j++;
  46977. }
  46978. }
  46979. while (p < positions.length) {
  46980. positions[p] = points[i].x;
  46981. positions[p + 1] = points[i].y;
  46982. positions[p + 2] = points[i].z;
  46983. p += 3;
  46984. }
  46985. };
  46986. instance.updateMeshPositions(positionFunction, false);
  46987. return instance;
  46988. }
  46989. // dashed lines creation
  46990. var dashedLines = new BABYLON.LinesMesh(name, scene);
  46991. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  46992. vertexData.applyToMesh(dashedLines, options.updatable);
  46993. dashedLines.dashSize = dashSize;
  46994. dashedLines.gapSize = gapSize;
  46995. return dashedLines;
  46996. };
  46997. /**
  46998. * Creates an extruded shape mesh.
  46999. * 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.
  47000. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47001. *
  47002. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47003. * 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
  47004. * extruded along the Z axis.
  47005. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47006. * 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.
  47007. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47008. * 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
  47009. * 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
  47010. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47012. * 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).
  47013. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47014. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47016. */
  47017. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47018. if (scene === void 0) { scene = null; }
  47019. var path = options.path;
  47020. var shape = options.shape;
  47021. var scale = options.scale || 1;
  47022. var rotation = options.rotation || 0;
  47023. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47024. var updatable = options.updatable;
  47025. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47026. var instance = options.instance || null;
  47027. var invertUV = options.invertUV || false;
  47028. 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);
  47029. };
  47030. /**
  47031. * Creates an custom extruded shape mesh.
  47032. * 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.
  47033. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47034. *
  47035. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47036. * 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
  47037. * extruded along the Z axis.
  47038. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47039. * 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
  47040. * and the distance of this point from the begining of the path :
  47041. * ```javascript
  47042. * var rotationFunction = function(i, distance) {
  47043. * // do things
  47044. * return rotationValue; }
  47045. * ```
  47046. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47047. * 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
  47048. * and the distance of this point from the begining of the path :
  47049. * ```javascript
  47050. * var scaleFunction = function(i, distance) {
  47051. * // do things
  47052. * return scaleValue;}
  47053. * ```
  47054. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47055. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47056. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47057. * 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
  47058. * 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
  47059. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47060. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47061. * 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).
  47062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47063. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47065. */
  47066. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47067. var path = options.path;
  47068. var shape = options.shape;
  47069. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47070. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47071. var ribbonCloseArray = options.ribbonCloseArray || false;
  47072. var ribbonClosePath = options.ribbonClosePath || false;
  47073. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47074. var updatable = options.updatable;
  47075. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47076. var instance = options.instance;
  47077. var invertUV = options.invertUV || false;
  47078. 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);
  47079. };
  47080. /**
  47081. * Creates lathe mesh.
  47082. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47083. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47084. *
  47085. * 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
  47086. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47087. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47088. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47089. * 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.
  47090. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47091. * 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
  47092. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47093. * 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).
  47094. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47095. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47097. */
  47098. MeshBuilder.CreateLathe = function (name, options, scene) {
  47099. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47100. var closed = (options.closed === undefined) ? true : options.closed;
  47101. var shape = options.shape;
  47102. var radius = options.radius || 1;
  47103. var tessellation = options.tessellation || 64;
  47104. var updatable = options.updatable;
  47105. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47106. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47107. var pi2 = Math.PI * 2;
  47108. var paths = new Array();
  47109. var invertUV = options.invertUV || false;
  47110. var i = 0;
  47111. var p = 0;
  47112. var step = pi2 / tessellation * arc;
  47113. var rotated;
  47114. var path = new Array();
  47115. ;
  47116. for (i = 0; i <= tessellation; i++) {
  47117. var path = [];
  47118. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47119. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47120. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47121. }
  47122. for (p = 0; p < shape.length; p++) {
  47123. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47124. path.push(rotated);
  47125. }
  47126. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47127. 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));
  47128. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47129. }
  47130. paths.push(path);
  47131. }
  47132. // lathe ribbon
  47133. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47134. return lathe;
  47135. };
  47136. /**
  47137. * Creates a plane mesh.
  47138. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47139. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47140. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47141. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47142. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47143. * 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).
  47144. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47145. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47146. */
  47147. MeshBuilder.CreatePlane = function (name, options, scene) {
  47148. var plane = new BABYLON.Mesh(name, scene);
  47149. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47150. plane._originalBuilderSideOrientation = options.sideOrientation;
  47151. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47152. vertexData.applyToMesh(plane, options.updatable);
  47153. if (options.sourcePlane) {
  47154. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47155. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47156. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47157. plane.rotate(vectorProduct, product);
  47158. }
  47159. return plane;
  47160. };
  47161. /**
  47162. * Creates a ground mesh.
  47163. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47164. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47165. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47166. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47167. */
  47168. MeshBuilder.CreateGround = function (name, options, scene) {
  47169. var ground = new BABYLON.GroundMesh(name, scene);
  47170. ground._setReady(false);
  47171. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47172. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47173. ground._width = options.width || 1;
  47174. ground._height = options.height || 1;
  47175. ground._maxX = ground._width / 2;
  47176. ground._maxZ = ground._height / 2;
  47177. ground._minX = -ground._maxX;
  47178. ground._minZ = -ground._maxZ;
  47179. var vertexData = BABYLON.VertexData.CreateGround(options);
  47180. vertexData.applyToMesh(ground, options.updatable);
  47181. ground._setReady(true);
  47182. return ground;
  47183. };
  47184. /**
  47185. * Creates a tiled ground mesh.
  47186. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47187. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47188. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47189. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47190. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47191. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47192. * numbers of subdivisions on the ground width and height of each tile.
  47193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47194. */
  47195. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47196. var tiledGround = new BABYLON.Mesh(name, scene);
  47197. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47198. vertexData.applyToMesh(tiledGround, options.updatable);
  47199. return tiledGround;
  47200. };
  47201. /**
  47202. * Creates a ground mesh from a height map.
  47203. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47204. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47205. * The parameter `url` sets the URL of the height map image resource.
  47206. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47207. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47208. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47209. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47210. * 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.
  47211. * 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).
  47212. * This function is passed the newly built mesh :
  47213. * ```javascript
  47214. * function(mesh) { // do things
  47215. * return; }
  47216. * ```
  47217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47218. */
  47219. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47220. var width = options.width || 10.0;
  47221. var height = options.height || 10.0;
  47222. var subdivisions = options.subdivisions || 1 | 0;
  47223. var minHeight = options.minHeight || 0.0;
  47224. var maxHeight = options.maxHeight || 1.0;
  47225. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47226. var updatable = options.updatable;
  47227. var onReady = options.onReady;
  47228. var ground = new BABYLON.GroundMesh(name, scene);
  47229. ground._subdivisionsX = subdivisions;
  47230. ground._subdivisionsY = subdivisions;
  47231. ground._width = width;
  47232. ground._height = height;
  47233. ground._maxX = ground._width / 2.0;
  47234. ground._maxZ = ground._height / 2.0;
  47235. ground._minX = -ground._maxX;
  47236. ground._minZ = -ground._maxZ;
  47237. ground._setReady(false);
  47238. var onload = function (img) {
  47239. // Getting height map data
  47240. var canvas = document.createElement("canvas");
  47241. var context = canvas.getContext("2d");
  47242. if (!context) {
  47243. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47244. }
  47245. var bufferWidth = img.width;
  47246. var bufferHeight = img.height;
  47247. canvas.width = bufferWidth;
  47248. canvas.height = bufferHeight;
  47249. context.drawImage(img, 0, 0);
  47250. // Create VertexData from map data
  47251. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47252. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47253. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47254. width: width, height: height,
  47255. subdivisions: subdivisions,
  47256. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47257. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47258. });
  47259. vertexData.applyToMesh(ground, updatable);
  47260. ground._setReady(true);
  47261. //execute ready callback, if set
  47262. if (onReady) {
  47263. onReady(ground);
  47264. }
  47265. };
  47266. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47267. return ground;
  47268. };
  47269. /**
  47270. * Creates a polygon mesh.
  47271. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47272. * 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.
  47273. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47275. * 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).
  47276. * Remember you can only change the shape positions, not their number when updating a polygon.
  47277. */
  47278. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47279. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47280. var shape = options.shape;
  47281. var holes = options.holes || [];
  47282. var depth = options.depth || 0;
  47283. var contours = [];
  47284. var hole = [];
  47285. for (var i = 0; i < shape.length; i++) {
  47286. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47287. }
  47288. var epsilon = 0.00000001;
  47289. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47290. contours.pop();
  47291. }
  47292. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47293. for (var hNb = 0; hNb < holes.length; hNb++) {
  47294. hole = [];
  47295. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47296. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47297. }
  47298. polygonTriangulation.addHole(hole);
  47299. }
  47300. var polygon = polygonTriangulation.build(options.updatable, depth);
  47301. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47302. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47303. vertexData.applyToMesh(polygon, options.updatable);
  47304. return polygon;
  47305. };
  47306. ;
  47307. /**
  47308. * Creates an extruded polygon mesh, with depth in the Y direction.
  47309. * 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).
  47310. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47311. */
  47312. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47313. return MeshBuilder.CreatePolygon(name, options, scene);
  47314. };
  47315. ;
  47316. /**
  47317. * Creates a tube mesh.
  47318. * 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.
  47319. *
  47320. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47321. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47322. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47323. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47324. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47325. * 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.
  47326. * It must return a radius value (positive float) :
  47327. * ```javascript
  47328. * var radiusFunction = function(i, distance) {
  47329. * // do things
  47330. * return radius; }
  47331. * ```
  47332. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47333. * 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
  47334. * 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
  47335. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47336. * 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).
  47337. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47338. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47340. */
  47341. MeshBuilder.CreateTube = function (name, options, scene) {
  47342. var path = options.path;
  47343. var instance = options.instance;
  47344. var radius = 1.0;
  47345. if (instance) {
  47346. radius = instance.radius;
  47347. }
  47348. if (options.radius !== undefined) {
  47349. radius = options.radius;
  47350. }
  47351. ;
  47352. var tessellation = options.tessellation || 64 | 0;
  47353. var radiusFunction = options.radiusFunction || null;
  47354. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47355. var invertUV = options.invertUV || false;
  47356. var updatable = options.updatable;
  47357. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47358. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47359. // tube geometry
  47360. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47361. var tangents = path3D.getTangents();
  47362. var normals = path3D.getNormals();
  47363. var distances = path3D.getDistances();
  47364. var pi2 = Math.PI * 2;
  47365. var step = pi2 / tessellation * arc;
  47366. var returnRadius = function () { return radius; };
  47367. var radiusFunctionFinal = radiusFunction || returnRadius;
  47368. var circlePath;
  47369. var rad;
  47370. var normal;
  47371. var rotated;
  47372. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47373. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47374. for (var i = 0; i < path.length; i++) {
  47375. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47376. circlePath = Array(); // current circle array
  47377. normal = normals[i]; // current normal
  47378. for (var t = 0; t < tessellation; t++) {
  47379. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47380. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47381. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47382. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47383. circlePath[t] = rotated;
  47384. }
  47385. circlePaths[index] = circlePath;
  47386. index++;
  47387. }
  47388. // cap
  47389. var capPath = function (nbPoints, pathIndex) {
  47390. var pointCap = Array();
  47391. for (var i = 0; i < nbPoints; i++) {
  47392. pointCap.push(path[pathIndex]);
  47393. }
  47394. return pointCap;
  47395. };
  47396. switch (cap) {
  47397. case BABYLON.Mesh.NO_CAP:
  47398. break;
  47399. case BABYLON.Mesh.CAP_START:
  47400. circlePaths[0] = capPath(tessellation, 0);
  47401. circlePaths[1] = circlePaths[2].slice(0);
  47402. break;
  47403. case BABYLON.Mesh.CAP_END:
  47404. circlePaths[index] = circlePaths[index - 1].slice(0);
  47405. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47406. break;
  47407. case BABYLON.Mesh.CAP_ALL:
  47408. circlePaths[0] = capPath(tessellation, 0);
  47409. circlePaths[1] = circlePaths[2].slice(0);
  47410. circlePaths[index] = circlePaths[index - 1].slice(0);
  47411. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47412. break;
  47413. default:
  47414. break;
  47415. }
  47416. return circlePaths;
  47417. };
  47418. var path3D;
  47419. var pathArray;
  47420. if (instance) {
  47421. var arc = options.arc || instance.arc;
  47422. path3D = (instance.path3D).update(path);
  47423. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47424. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47425. instance.path3D = path3D;
  47426. instance.pathArray = pathArray;
  47427. instance.arc = arc;
  47428. instance.radius = radius;
  47429. return instance;
  47430. }
  47431. // tube creation
  47432. path3D = new BABYLON.Path3D(path);
  47433. var newPathArray = new Array();
  47434. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47435. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47436. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47437. tube.pathArray = pathArray;
  47438. tube.path3D = path3D;
  47439. tube.tessellation = tessellation;
  47440. tube.cap = cap;
  47441. tube.arc = options.arc;
  47442. tube.radius = radius;
  47443. return tube;
  47444. };
  47445. /**
  47446. * Creates a polyhedron mesh.
  47447. *
  47448. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47449. * 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
  47450. * to choose the wanted type.
  47451. * The parameter `size` (positive float, default 1) sets the polygon size.
  47452. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47453. * 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`.
  47454. * 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
  47455. * 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)`).
  47456. * 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
  47457. * 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.
  47458. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47459. * 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).
  47460. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47462. */
  47463. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47464. var polyhedron = new BABYLON.Mesh(name, scene);
  47465. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47466. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47467. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47468. vertexData.applyToMesh(polyhedron, options.updatable);
  47469. return polyhedron;
  47470. };
  47471. /**
  47472. * Creates a decal mesh.
  47473. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47474. * 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.
  47475. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47476. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47477. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47478. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47479. */
  47480. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47481. var indices = sourceMesh.getIndices();
  47482. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47483. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47484. var position = options.position || BABYLON.Vector3.Zero();
  47485. var normal = options.normal || BABYLON.Vector3.Up();
  47486. var size = options.size || BABYLON.Vector3.One();
  47487. var angle = options.angle || 0;
  47488. // Getting correct rotation
  47489. if (!normal) {
  47490. var target = new BABYLON.Vector3(0, 0, 1);
  47491. var camera = sourceMesh.getScene().activeCamera;
  47492. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47493. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47494. }
  47495. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47496. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47497. var pitch = Math.atan2(normal.y, len);
  47498. // Matrix
  47499. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47500. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47501. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47502. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47503. var vertexData = new BABYLON.VertexData();
  47504. vertexData.indices = [];
  47505. vertexData.positions = [];
  47506. vertexData.normals = [];
  47507. vertexData.uvs = [];
  47508. var currentVertexDataIndex = 0;
  47509. var extractDecalVector3 = function (indexId) {
  47510. var result = new BABYLON.PositionNormalVertex();
  47511. if (!indices || !positions || !normals) {
  47512. return result;
  47513. }
  47514. var vertexId = indices[indexId];
  47515. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47516. // Send vector to decal local world
  47517. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47518. // Get normal
  47519. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47520. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47521. return result;
  47522. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47523. var clip = function (vertices, axis) {
  47524. if (vertices.length === 0) {
  47525. return vertices;
  47526. }
  47527. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47528. var clipVertices = function (v0, v1) {
  47529. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47530. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47531. };
  47532. var result = new Array();
  47533. for (var index = 0; index < vertices.length; index += 3) {
  47534. var v1Out;
  47535. var v2Out;
  47536. var v3Out;
  47537. var total = 0;
  47538. var nV1 = null;
  47539. var nV2 = null;
  47540. var nV3 = null;
  47541. var nV4 = null;
  47542. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47543. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47544. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47545. v1Out = d1 > 0;
  47546. v2Out = d2 > 0;
  47547. v3Out = d3 > 0;
  47548. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47549. switch (total) {
  47550. case 0:
  47551. result.push(vertices[index]);
  47552. result.push(vertices[index + 1]);
  47553. result.push(vertices[index + 2]);
  47554. break;
  47555. case 1:
  47556. if (v1Out) {
  47557. nV1 = vertices[index + 1];
  47558. nV2 = vertices[index + 2];
  47559. nV3 = clipVertices(vertices[index], nV1);
  47560. nV4 = clipVertices(vertices[index], nV2);
  47561. }
  47562. if (v2Out) {
  47563. nV1 = vertices[index];
  47564. nV2 = vertices[index + 2];
  47565. nV3 = clipVertices(vertices[index + 1], nV1);
  47566. nV4 = clipVertices(vertices[index + 1], nV2);
  47567. result.push(nV3);
  47568. result.push(nV2.clone());
  47569. result.push(nV1.clone());
  47570. result.push(nV2.clone());
  47571. result.push(nV3.clone());
  47572. result.push(nV4);
  47573. break;
  47574. }
  47575. if (v3Out) {
  47576. nV1 = vertices[index];
  47577. nV2 = vertices[index + 1];
  47578. nV3 = clipVertices(vertices[index + 2], nV1);
  47579. nV4 = clipVertices(vertices[index + 2], nV2);
  47580. }
  47581. if (nV1 && nV2 && nV3 && nV4) {
  47582. result.push(nV1.clone());
  47583. result.push(nV2.clone());
  47584. result.push(nV3);
  47585. result.push(nV4);
  47586. result.push(nV3.clone());
  47587. result.push(nV2.clone());
  47588. }
  47589. break;
  47590. case 2:
  47591. if (!v1Out) {
  47592. nV1 = vertices[index].clone();
  47593. nV2 = clipVertices(nV1, vertices[index + 1]);
  47594. nV3 = clipVertices(nV1, vertices[index + 2]);
  47595. result.push(nV1);
  47596. result.push(nV2);
  47597. result.push(nV3);
  47598. }
  47599. if (!v2Out) {
  47600. nV1 = vertices[index + 1].clone();
  47601. nV2 = clipVertices(nV1, vertices[index + 2]);
  47602. nV3 = clipVertices(nV1, vertices[index]);
  47603. result.push(nV1);
  47604. result.push(nV2);
  47605. result.push(nV3);
  47606. }
  47607. if (!v3Out) {
  47608. nV1 = vertices[index + 2].clone();
  47609. nV2 = clipVertices(nV1, vertices[index]);
  47610. nV3 = clipVertices(nV1, vertices[index + 1]);
  47611. result.push(nV1);
  47612. result.push(nV2);
  47613. result.push(nV3);
  47614. }
  47615. break;
  47616. case 3:
  47617. break;
  47618. }
  47619. }
  47620. return result;
  47621. };
  47622. for (var index = 0; index < indices.length; index += 3) {
  47623. var faceVertices = new Array();
  47624. faceVertices.push(extractDecalVector3(index));
  47625. faceVertices.push(extractDecalVector3(index + 1));
  47626. faceVertices.push(extractDecalVector3(index + 2));
  47627. // Clip
  47628. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  47629. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  47630. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  47631. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  47632. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  47633. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  47634. if (faceVertices.length === 0) {
  47635. continue;
  47636. }
  47637. // Add UVs and get back to world
  47638. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  47639. var vertex = faceVertices[vIndex];
  47640. //TODO check for Int32Array | Uint32Array | Uint16Array
  47641. vertexData.indices.push(currentVertexDataIndex);
  47642. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  47643. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  47644. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  47645. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  47646. currentVertexDataIndex++;
  47647. }
  47648. }
  47649. // Return mesh
  47650. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  47651. vertexData.applyToMesh(decal);
  47652. decal.position = position.clone();
  47653. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  47654. return decal;
  47655. };
  47656. // Privates
  47657. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  47658. // extrusion geometry
  47659. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  47660. var tangents = path3D.getTangents();
  47661. var normals = path3D.getNormals();
  47662. var binormals = path3D.getBinormals();
  47663. var distances = path3D.getDistances();
  47664. var angle = 0;
  47665. var returnScale = function () { return scale !== null ? scale : 1; };
  47666. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  47667. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  47668. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  47669. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47670. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47671. for (var i = 0; i < curve.length; i++) {
  47672. var shapePath = new Array();
  47673. var angleStep = rotate(i, distances[i]);
  47674. var scaleRatio = scl(i, distances[i]);
  47675. for (var p = 0; p < shape.length; p++) {
  47676. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  47677. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  47678. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  47679. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  47680. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  47681. shapePath[p] = rotated;
  47682. }
  47683. shapePaths[index] = shapePath;
  47684. angle += angleStep;
  47685. index++;
  47686. }
  47687. // cap
  47688. var capPath = function (shapePath) {
  47689. var pointCap = Array();
  47690. var barycenter = BABYLON.Vector3.Zero();
  47691. var i;
  47692. for (i = 0; i < shapePath.length; i++) {
  47693. barycenter.addInPlace(shapePath[i]);
  47694. }
  47695. barycenter.scaleInPlace(1.0 / shapePath.length);
  47696. for (i = 0; i < shapePath.length; i++) {
  47697. pointCap.push(barycenter);
  47698. }
  47699. return pointCap;
  47700. };
  47701. switch (cap) {
  47702. case BABYLON.Mesh.NO_CAP:
  47703. break;
  47704. case BABYLON.Mesh.CAP_START:
  47705. shapePaths[0] = capPath(shapePaths[2]);
  47706. shapePaths[1] = shapePaths[2];
  47707. break;
  47708. case BABYLON.Mesh.CAP_END:
  47709. shapePaths[index] = shapePaths[index - 1];
  47710. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47711. break;
  47712. case BABYLON.Mesh.CAP_ALL:
  47713. shapePaths[0] = capPath(shapePaths[2]);
  47714. shapePaths[1] = shapePaths[2];
  47715. shapePaths[index] = shapePaths[index - 1];
  47716. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47717. break;
  47718. default:
  47719. break;
  47720. }
  47721. return shapePaths;
  47722. };
  47723. var path3D;
  47724. var pathArray;
  47725. if (instance) {
  47726. path3D = (instance.path3D).update(curve);
  47727. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  47728. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  47729. return instance;
  47730. }
  47731. // extruded shape creation
  47732. path3D = new BABYLON.Path3D(curve);
  47733. var newShapePaths = new Array();
  47734. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47735. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  47736. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  47737. extrudedGeneric.pathArray = pathArray;
  47738. extrudedGeneric.path3D = path3D;
  47739. extrudedGeneric.cap = cap;
  47740. return extrudedGeneric;
  47741. };
  47742. return MeshBuilder;
  47743. }());
  47744. BABYLON.MeshBuilder = MeshBuilder;
  47745. })(BABYLON || (BABYLON = {}));
  47746. //# sourceMappingURL=babylon.meshBuilder.js.map
  47747. var BABYLON;
  47748. (function (BABYLON) {
  47749. var AudioEngine = /** @class */ (function () {
  47750. function AudioEngine() {
  47751. this._audioContext = null;
  47752. this._audioContextInitialized = false;
  47753. this.canUseWebAudio = false;
  47754. this.WarnedWebAudioUnsupported = false;
  47755. this.unlocked = false;
  47756. this.isMP3supported = false;
  47757. this.isOGGsupported = false;
  47758. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  47759. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  47760. this.canUseWebAudio = true;
  47761. }
  47762. var audioElem = document.createElement('audio');
  47763. try {
  47764. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  47765. this.isMP3supported = true;
  47766. }
  47767. }
  47768. catch (e) {
  47769. // protect error during capability check.
  47770. }
  47771. try {
  47772. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  47773. this.isOGGsupported = true;
  47774. }
  47775. }
  47776. catch (e) {
  47777. // protect error during capability check.
  47778. }
  47779. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  47780. this._unlockiOSaudio();
  47781. }
  47782. else {
  47783. this.unlocked = true;
  47784. }
  47785. }
  47786. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  47787. get: function () {
  47788. if (!this._audioContextInitialized) {
  47789. this._initializeAudioContext();
  47790. }
  47791. return this._audioContext;
  47792. },
  47793. enumerable: true,
  47794. configurable: true
  47795. });
  47796. AudioEngine.prototype._unlockiOSaudio = function () {
  47797. var _this = this;
  47798. var unlockaudio = function () {
  47799. if (!_this.audioContext) {
  47800. return;
  47801. }
  47802. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  47803. var source = _this.audioContext.createBufferSource();
  47804. source.buffer = buffer;
  47805. source.connect(_this.audioContext.destination);
  47806. source.start(0);
  47807. setTimeout(function () {
  47808. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  47809. _this.unlocked = true;
  47810. window.removeEventListener('touchend', unlockaudio, false);
  47811. if (_this.onAudioUnlocked) {
  47812. _this.onAudioUnlocked();
  47813. }
  47814. }
  47815. }, 0);
  47816. };
  47817. window.addEventListener('touchend', unlockaudio, false);
  47818. };
  47819. AudioEngine.prototype._initializeAudioContext = function () {
  47820. try {
  47821. if (this.canUseWebAudio) {
  47822. this._audioContext = new AudioContext();
  47823. // create a global volume gain node
  47824. this.masterGain = this._audioContext.createGain();
  47825. this.masterGain.gain.value = 1;
  47826. this.masterGain.connect(this._audioContext.destination);
  47827. this._audioContextInitialized = true;
  47828. }
  47829. }
  47830. catch (e) {
  47831. this.canUseWebAudio = false;
  47832. BABYLON.Tools.Error("Web Audio: " + e.message);
  47833. }
  47834. };
  47835. AudioEngine.prototype.dispose = function () {
  47836. if (this.canUseWebAudio && this._audioContextInitialized) {
  47837. if (this._connectedAnalyser && this._audioContext) {
  47838. this._connectedAnalyser.stopDebugCanvas();
  47839. this._connectedAnalyser.dispose();
  47840. this.masterGain.disconnect();
  47841. this.masterGain.connect(this._audioContext.destination);
  47842. this._connectedAnalyser = null;
  47843. }
  47844. this.masterGain.gain.value = 1;
  47845. }
  47846. this.WarnedWebAudioUnsupported = false;
  47847. };
  47848. AudioEngine.prototype.getGlobalVolume = function () {
  47849. if (this.canUseWebAudio && this._audioContextInitialized) {
  47850. return this.masterGain.gain.value;
  47851. }
  47852. else {
  47853. return -1;
  47854. }
  47855. };
  47856. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  47857. if (this.canUseWebAudio && this._audioContextInitialized) {
  47858. this.masterGain.gain.value = newVolume;
  47859. }
  47860. };
  47861. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  47862. if (this._connectedAnalyser) {
  47863. this._connectedAnalyser.stopDebugCanvas();
  47864. }
  47865. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  47866. this._connectedAnalyser = analyser;
  47867. this.masterGain.disconnect();
  47868. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  47869. }
  47870. };
  47871. return AudioEngine;
  47872. }());
  47873. BABYLON.AudioEngine = AudioEngine;
  47874. })(BABYLON || (BABYLON = {}));
  47875. //# sourceMappingURL=babylon.audioEngine.js.map
  47876. var BABYLON;
  47877. (function (BABYLON) {
  47878. var Sound = /** @class */ (function () {
  47879. /**
  47880. * Create a sound and attach it to a scene
  47881. * @param name Name of your sound
  47882. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  47883. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  47884. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  47885. */
  47886. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  47887. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  47888. var _this = this;
  47889. this.autoplay = false;
  47890. this.loop = false;
  47891. this.useCustomAttenuation = false;
  47892. this.spatialSound = false;
  47893. this.refDistance = 1;
  47894. this.rolloffFactor = 1;
  47895. this.maxDistance = 100;
  47896. this.distanceModel = "linear";
  47897. this._panningModel = "equalpower";
  47898. this._playbackRate = 1;
  47899. this._streaming = false;
  47900. this._startTime = 0;
  47901. this._startOffset = 0;
  47902. this._position = BABYLON.Vector3.Zero();
  47903. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  47904. this._volume = 1;
  47905. this._isLoaded = false;
  47906. this._isReadyToPlay = false;
  47907. this.isPlaying = false;
  47908. this.isPaused = false;
  47909. this._isDirectional = false;
  47910. // Used if you'd like to create a directional sound.
  47911. // If not set, the sound will be omnidirectional
  47912. this._coneInnerAngle = 360;
  47913. this._coneOuterAngle = 360;
  47914. this._coneOuterGain = 0;
  47915. this._isOutputConnected = false;
  47916. this._urlType = "Unknown";
  47917. this.name = name;
  47918. this._scene = scene;
  47919. this._readyToPlayCallback = readyToPlayCallback;
  47920. // Default custom attenuation function is a linear attenuation
  47921. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  47922. if (currentDistance < maxDistance) {
  47923. return currentVolume * (1 - currentDistance / maxDistance);
  47924. }
  47925. else {
  47926. return 0;
  47927. }
  47928. };
  47929. if (options) {
  47930. this.autoplay = options.autoplay || false;
  47931. this.loop = options.loop || false;
  47932. // if volume === 0, we need another way to check this option
  47933. if (options.volume !== undefined) {
  47934. this._volume = options.volume;
  47935. }
  47936. this.spatialSound = options.spatialSound || false;
  47937. this.maxDistance = options.maxDistance || 100;
  47938. this.useCustomAttenuation = options.useCustomAttenuation || false;
  47939. this.rolloffFactor = options.rolloffFactor || 1;
  47940. this.refDistance = options.refDistance || 1;
  47941. this.distanceModel = options.distanceModel || "linear";
  47942. this._playbackRate = options.playbackRate || 1;
  47943. this._streaming = options.streaming || false;
  47944. }
  47945. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  47946. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  47947. this._soundGain.gain.value = this._volume;
  47948. this._inputAudioNode = this._soundGain;
  47949. this._ouputAudioNode = this._soundGain;
  47950. if (this.spatialSound) {
  47951. this._createSpatialParameters();
  47952. }
  47953. this._scene.mainSoundTrack.AddSound(this);
  47954. var validParameter = true;
  47955. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  47956. if (urlOrArrayBuffer) {
  47957. if (typeof (urlOrArrayBuffer) === "string")
  47958. this._urlType = "String";
  47959. if (Array.isArray(urlOrArrayBuffer))
  47960. this._urlType = "Array";
  47961. if (urlOrArrayBuffer instanceof ArrayBuffer)
  47962. this._urlType = "ArrayBuffer";
  47963. var urls = [];
  47964. var codecSupportedFound = false;
  47965. switch (this._urlType) {
  47966. case "ArrayBuffer":
  47967. if (urlOrArrayBuffer.byteLength > 0) {
  47968. codecSupportedFound = true;
  47969. this._soundLoaded(urlOrArrayBuffer);
  47970. }
  47971. break;
  47972. case "String":
  47973. urls.push(urlOrArrayBuffer);
  47974. case "Array":
  47975. if (urls.length === 0)
  47976. urls = urlOrArrayBuffer;
  47977. // If we found a supported format, we load it immediately and stop the loop
  47978. for (var i = 0; i < urls.length; i++) {
  47979. var url = urls[i];
  47980. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  47981. codecSupportedFound = true;
  47982. }
  47983. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  47984. codecSupportedFound = true;
  47985. }
  47986. if (url.indexOf(".wav", url.length - 4) !== -1) {
  47987. codecSupportedFound = true;
  47988. }
  47989. if (url.indexOf("blob:") !== -1) {
  47990. codecSupportedFound = true;
  47991. }
  47992. if (codecSupportedFound) {
  47993. // Loading sound using XHR2
  47994. if (!this._streaming) {
  47995. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  47996. }
  47997. else {
  47998. this._htmlAudioElement = new Audio(url);
  47999. this._htmlAudioElement.controls = false;
  48000. this._htmlAudioElement.loop = this.loop;
  48001. this._htmlAudioElement.crossOrigin = "anonymous";
  48002. this._htmlAudioElement.preload = "auto";
  48003. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48004. _this._isReadyToPlay = true;
  48005. if (_this.autoplay) {
  48006. _this.play();
  48007. }
  48008. if (_this._readyToPlayCallback) {
  48009. _this._readyToPlayCallback();
  48010. }
  48011. });
  48012. document.body.appendChild(this._htmlAudioElement);
  48013. }
  48014. break;
  48015. }
  48016. }
  48017. break;
  48018. default:
  48019. validParameter = false;
  48020. break;
  48021. }
  48022. if (!validParameter) {
  48023. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48024. }
  48025. else {
  48026. if (!codecSupportedFound) {
  48027. this._isReadyToPlay = true;
  48028. // Simulating a ready to play event to avoid breaking code path
  48029. if (this._readyToPlayCallback) {
  48030. window.setTimeout(function () {
  48031. if (_this._readyToPlayCallback) {
  48032. _this._readyToPlayCallback();
  48033. }
  48034. }, 1000);
  48035. }
  48036. }
  48037. }
  48038. }
  48039. }
  48040. else {
  48041. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48042. this._scene.mainSoundTrack.AddSound(this);
  48043. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48044. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48045. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48046. }
  48047. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48048. if (this._readyToPlayCallback) {
  48049. window.setTimeout(function () {
  48050. if (_this._readyToPlayCallback) {
  48051. _this._readyToPlayCallback();
  48052. }
  48053. }, 1000);
  48054. }
  48055. }
  48056. }
  48057. Sound.prototype.dispose = function () {
  48058. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48059. if (this.isPlaying) {
  48060. this.stop();
  48061. }
  48062. this._isReadyToPlay = false;
  48063. if (this.soundTrackId === -1) {
  48064. this._scene.mainSoundTrack.RemoveSound(this);
  48065. }
  48066. else {
  48067. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48068. }
  48069. if (this._soundGain) {
  48070. this._soundGain.disconnect();
  48071. this._soundGain = null;
  48072. }
  48073. if (this._soundPanner) {
  48074. this._soundPanner.disconnect();
  48075. this._soundPanner = null;
  48076. }
  48077. if (this._soundSource) {
  48078. this._soundSource.disconnect();
  48079. this._soundSource = null;
  48080. }
  48081. this._audioBuffer = null;
  48082. if (this._htmlAudioElement) {
  48083. this._htmlAudioElement.pause();
  48084. this._htmlAudioElement.src = "";
  48085. document.body.removeChild(this._htmlAudioElement);
  48086. }
  48087. if (this._connectedMesh && this._registerFunc) {
  48088. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48089. this._connectedMesh = null;
  48090. }
  48091. }
  48092. };
  48093. Sound.prototype.isReady = function () {
  48094. return this._isReadyToPlay;
  48095. };
  48096. Sound.prototype._soundLoaded = function (audioData) {
  48097. var _this = this;
  48098. this._isLoaded = true;
  48099. if (!BABYLON.Engine.audioEngine.audioContext) {
  48100. return;
  48101. }
  48102. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48103. _this._audioBuffer = buffer;
  48104. _this._isReadyToPlay = true;
  48105. if (_this.autoplay) {
  48106. _this.play();
  48107. }
  48108. if (_this._readyToPlayCallback) {
  48109. _this._readyToPlayCallback();
  48110. }
  48111. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48112. };
  48113. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48114. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48115. this._audioBuffer = audioBuffer;
  48116. this._isReadyToPlay = true;
  48117. }
  48118. };
  48119. Sound.prototype.updateOptions = function (options) {
  48120. if (options) {
  48121. this.loop = options.loop || this.loop;
  48122. this.maxDistance = options.maxDistance || this.maxDistance;
  48123. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48124. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48125. this.refDistance = options.refDistance || this.refDistance;
  48126. this.distanceModel = options.distanceModel || this.distanceModel;
  48127. this._playbackRate = options.playbackRate || this._playbackRate;
  48128. this._updateSpatialParameters();
  48129. if (this.isPlaying) {
  48130. if (this._streaming) {
  48131. this._htmlAudioElement.playbackRate = this._playbackRate;
  48132. }
  48133. else {
  48134. if (this._soundSource) {
  48135. this._soundSource.playbackRate.value = this._playbackRate;
  48136. }
  48137. }
  48138. }
  48139. }
  48140. };
  48141. Sound.prototype._createSpatialParameters = function () {
  48142. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48143. if (this._scene.headphone) {
  48144. this._panningModel = "HRTF";
  48145. }
  48146. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48147. this._updateSpatialParameters();
  48148. this._soundPanner.connect(this._ouputAudioNode);
  48149. this._inputAudioNode = this._soundPanner;
  48150. }
  48151. };
  48152. Sound.prototype._updateSpatialParameters = function () {
  48153. if (this.spatialSound && this._soundPanner) {
  48154. if (this.useCustomAttenuation) {
  48155. // Tricks to disable in a way embedded Web Audio attenuation
  48156. this._soundPanner.distanceModel = "linear";
  48157. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48158. this._soundPanner.refDistance = 1;
  48159. this._soundPanner.rolloffFactor = 1;
  48160. this._soundPanner.panningModel = this._panningModel;
  48161. }
  48162. else {
  48163. this._soundPanner.distanceModel = this.distanceModel;
  48164. this._soundPanner.maxDistance = this.maxDistance;
  48165. this._soundPanner.refDistance = this.refDistance;
  48166. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48167. this._soundPanner.panningModel = this._panningModel;
  48168. }
  48169. }
  48170. };
  48171. Sound.prototype.switchPanningModelToHRTF = function () {
  48172. this._panningModel = "HRTF";
  48173. this._switchPanningModel();
  48174. };
  48175. Sound.prototype.switchPanningModelToEqualPower = function () {
  48176. this._panningModel = "equalpower";
  48177. this._switchPanningModel();
  48178. };
  48179. Sound.prototype._switchPanningModel = function () {
  48180. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48181. this._soundPanner.panningModel = this._panningModel;
  48182. }
  48183. };
  48184. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48185. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48186. if (this._isOutputConnected) {
  48187. this._ouputAudioNode.disconnect();
  48188. }
  48189. this._ouputAudioNode.connect(soundTrackAudioNode);
  48190. this._isOutputConnected = true;
  48191. }
  48192. };
  48193. /**
  48194. * Transform this sound into a directional source
  48195. * @param coneInnerAngle Size of the inner cone in degree
  48196. * @param coneOuterAngle Size of the outer cone in degree
  48197. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48198. */
  48199. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48200. if (coneOuterAngle < coneInnerAngle) {
  48201. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48202. return;
  48203. }
  48204. this._coneInnerAngle = coneInnerAngle;
  48205. this._coneOuterAngle = coneOuterAngle;
  48206. this._coneOuterGain = coneOuterGain;
  48207. this._isDirectional = true;
  48208. if (this.isPlaying && this.loop) {
  48209. this.stop();
  48210. this.play();
  48211. }
  48212. };
  48213. Sound.prototype.setPosition = function (newPosition) {
  48214. this._position = newPosition;
  48215. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48216. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48217. }
  48218. };
  48219. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48220. this._localDirection = newLocalDirection;
  48221. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48222. this._updateDirection();
  48223. }
  48224. };
  48225. Sound.prototype._updateDirection = function () {
  48226. if (!this._connectedMesh || !this._soundPanner) {
  48227. return;
  48228. }
  48229. var mat = this._connectedMesh.getWorldMatrix();
  48230. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48231. direction.normalize();
  48232. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48233. };
  48234. Sound.prototype.updateDistanceFromListener = function () {
  48235. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48236. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48237. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48238. }
  48239. };
  48240. Sound.prototype.setAttenuationFunction = function (callback) {
  48241. this._customAttenuationFunction = callback;
  48242. };
  48243. /**
  48244. * Play the sound
  48245. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48246. * @param offset (optional) Start the sound setting it at a specific time
  48247. */
  48248. Sound.prototype.play = function (time, offset) {
  48249. var _this = this;
  48250. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48251. try {
  48252. if (this._startOffset < 0) {
  48253. time = -this._startOffset;
  48254. this._startOffset = 0;
  48255. }
  48256. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48257. if (!this._soundSource || !this._streamingSource) {
  48258. if (this.spatialSound && this._soundPanner) {
  48259. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48260. if (this._isDirectional) {
  48261. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48262. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48263. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48264. if (this._connectedMesh) {
  48265. this._updateDirection();
  48266. }
  48267. else {
  48268. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48269. }
  48270. }
  48271. }
  48272. }
  48273. if (this._streaming) {
  48274. if (!this._streamingSource) {
  48275. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48276. this._htmlAudioElement.onended = function () { _this._onended(); };
  48277. this._htmlAudioElement.playbackRate = this._playbackRate;
  48278. }
  48279. this._streamingSource.disconnect();
  48280. this._streamingSource.connect(this._inputAudioNode);
  48281. this._htmlAudioElement.play();
  48282. }
  48283. else {
  48284. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48285. this._soundSource.buffer = this._audioBuffer;
  48286. this._soundSource.connect(this._inputAudioNode);
  48287. this._soundSource.loop = this.loop;
  48288. this._soundSource.playbackRate.value = this._playbackRate;
  48289. this._soundSource.onended = function () { _this._onended(); };
  48290. if (this._soundSource.buffer) {
  48291. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48292. }
  48293. }
  48294. this._startTime = startTime;
  48295. this.isPlaying = true;
  48296. this.isPaused = false;
  48297. }
  48298. catch (ex) {
  48299. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48300. }
  48301. }
  48302. };
  48303. Sound.prototype._onended = function () {
  48304. this.isPlaying = false;
  48305. if (this.onended) {
  48306. this.onended();
  48307. }
  48308. };
  48309. /**
  48310. * Stop the sound
  48311. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48312. */
  48313. Sound.prototype.stop = function (time) {
  48314. if (this.isPlaying) {
  48315. if (this._streaming) {
  48316. this._htmlAudioElement.pause();
  48317. // Test needed for Firefox or it will generate an Invalid State Error
  48318. if (this._htmlAudioElement.currentTime > 0) {
  48319. this._htmlAudioElement.currentTime = 0;
  48320. }
  48321. }
  48322. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48323. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48324. this._soundSource.stop(stopTime);
  48325. this._soundSource.onended = function () { };
  48326. if (!this.isPaused) {
  48327. this._startOffset = 0;
  48328. }
  48329. }
  48330. this.isPlaying = false;
  48331. }
  48332. };
  48333. Sound.prototype.pause = function () {
  48334. if (this.isPlaying) {
  48335. this.isPaused = true;
  48336. if (this._streaming) {
  48337. this._htmlAudioElement.pause();
  48338. }
  48339. else if (BABYLON.Engine.audioEngine.audioContext) {
  48340. this.stop(0);
  48341. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48342. }
  48343. }
  48344. };
  48345. Sound.prototype.setVolume = function (newVolume, time) {
  48346. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48347. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48348. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48349. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48350. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48351. }
  48352. else {
  48353. this._soundGain.gain.value = newVolume;
  48354. }
  48355. }
  48356. this._volume = newVolume;
  48357. };
  48358. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48359. this._playbackRate = newPlaybackRate;
  48360. if (this.isPlaying) {
  48361. if (this._streaming) {
  48362. this._htmlAudioElement.playbackRate = this._playbackRate;
  48363. }
  48364. else if (this._soundSource) {
  48365. this._soundSource.playbackRate.value = this._playbackRate;
  48366. }
  48367. }
  48368. };
  48369. Sound.prototype.getVolume = function () {
  48370. return this._volume;
  48371. };
  48372. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48373. var _this = this;
  48374. if (this._connectedMesh && this._registerFunc) {
  48375. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48376. this._registerFunc = null;
  48377. }
  48378. this._connectedMesh = meshToConnectTo;
  48379. if (!this.spatialSound) {
  48380. this.spatialSound = true;
  48381. this._createSpatialParameters();
  48382. if (this.isPlaying && this.loop) {
  48383. this.stop();
  48384. this.play();
  48385. }
  48386. }
  48387. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48388. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48389. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48390. };
  48391. Sound.prototype.detachFromMesh = function () {
  48392. if (this._connectedMesh && this._registerFunc) {
  48393. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48394. this._registerFunc = null;
  48395. this._connectedMesh = null;
  48396. }
  48397. };
  48398. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48399. var boundingInfo = connectedMesh.getBoundingInfo();
  48400. if (!boundingInfo) {
  48401. return;
  48402. }
  48403. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48404. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48405. this._updateDirection();
  48406. }
  48407. };
  48408. Sound.prototype.clone = function () {
  48409. var _this = this;
  48410. if (!this._streaming) {
  48411. var setBufferAndRun = function () {
  48412. if (_this._isReadyToPlay) {
  48413. clonedSound._audioBuffer = _this.getAudioBuffer();
  48414. clonedSound._isReadyToPlay = true;
  48415. if (clonedSound.autoplay) {
  48416. clonedSound.play();
  48417. }
  48418. }
  48419. else {
  48420. window.setTimeout(setBufferAndRun, 300);
  48421. }
  48422. };
  48423. var currentOptions = {
  48424. autoplay: this.autoplay, loop: this.loop,
  48425. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48426. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48427. refDistance: this.refDistance, distanceModel: this.distanceModel
  48428. };
  48429. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48430. if (this.useCustomAttenuation) {
  48431. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48432. }
  48433. clonedSound.setPosition(this._position);
  48434. clonedSound.setPlaybackRate(this._playbackRate);
  48435. setBufferAndRun();
  48436. return clonedSound;
  48437. }
  48438. else {
  48439. return null;
  48440. }
  48441. };
  48442. Sound.prototype.getAudioBuffer = function () {
  48443. return this._audioBuffer;
  48444. };
  48445. Sound.prototype.serialize = function () {
  48446. var serializationObject = {
  48447. name: this.name,
  48448. url: this.name,
  48449. autoplay: this.autoplay,
  48450. loop: this.loop,
  48451. volume: this._volume,
  48452. spatialSound: this.spatialSound,
  48453. maxDistance: this.maxDistance,
  48454. rolloffFactor: this.rolloffFactor,
  48455. refDistance: this.refDistance,
  48456. distanceModel: this.distanceModel,
  48457. playbackRate: this._playbackRate,
  48458. panningModel: this._panningModel,
  48459. soundTrackId: this.soundTrackId
  48460. };
  48461. if (this.spatialSound) {
  48462. if (this._connectedMesh)
  48463. serializationObject.connectedMeshId = this._connectedMesh.id;
  48464. serializationObject.position = this._position.asArray();
  48465. serializationObject.refDistance = this.refDistance;
  48466. serializationObject.distanceModel = this.distanceModel;
  48467. serializationObject.isDirectional = this._isDirectional;
  48468. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48469. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48470. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48471. serializationObject.coneOuterGain = this._coneOuterGain;
  48472. }
  48473. return serializationObject;
  48474. };
  48475. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48476. var soundName = parsedSound.name;
  48477. var soundUrl;
  48478. if (parsedSound.url) {
  48479. soundUrl = rootUrl + parsedSound.url;
  48480. }
  48481. else {
  48482. soundUrl = rootUrl + soundName;
  48483. }
  48484. var options = {
  48485. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48486. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48487. rolloffFactor: parsedSound.rolloffFactor,
  48488. refDistance: parsedSound.refDistance,
  48489. distanceModel: parsedSound.distanceModel,
  48490. playbackRate: parsedSound.playbackRate
  48491. };
  48492. var newSound;
  48493. if (!sourceSound) {
  48494. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48495. scene._addPendingData(newSound);
  48496. }
  48497. else {
  48498. var setBufferAndRun = function () {
  48499. if (sourceSound._isReadyToPlay) {
  48500. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48501. newSound._isReadyToPlay = true;
  48502. if (newSound.autoplay) {
  48503. newSound.play();
  48504. }
  48505. }
  48506. else {
  48507. window.setTimeout(setBufferAndRun, 300);
  48508. }
  48509. };
  48510. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48511. setBufferAndRun();
  48512. }
  48513. if (parsedSound.position) {
  48514. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48515. newSound.setPosition(soundPosition);
  48516. }
  48517. if (parsedSound.isDirectional) {
  48518. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48519. if (parsedSound.localDirectionToMesh) {
  48520. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48521. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48522. }
  48523. }
  48524. if (parsedSound.connectedMeshId) {
  48525. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48526. if (connectedMesh) {
  48527. newSound.attachToMesh(connectedMesh);
  48528. }
  48529. }
  48530. return newSound;
  48531. };
  48532. return Sound;
  48533. }());
  48534. BABYLON.Sound = Sound;
  48535. })(BABYLON || (BABYLON = {}));
  48536. //# sourceMappingURL=babylon.sound.js.map
  48537. var BABYLON;
  48538. (function (BABYLON) {
  48539. var SoundTrack = /** @class */ (function () {
  48540. function SoundTrack(scene, options) {
  48541. this.id = -1;
  48542. this._isMainTrack = false;
  48543. this._isInitialized = false;
  48544. this._scene = scene;
  48545. this.soundCollection = new Array();
  48546. this._options = options;
  48547. if (!this._isMainTrack) {
  48548. this._scene.soundTracks.push(this);
  48549. this.id = this._scene.soundTracks.length - 1;
  48550. }
  48551. }
  48552. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48553. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48554. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48555. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48556. if (this._options) {
  48557. if (this._options.volume) {
  48558. this._outputAudioNode.gain.value = this._options.volume;
  48559. }
  48560. if (this._options.mainTrack) {
  48561. this._isMainTrack = this._options.mainTrack;
  48562. }
  48563. }
  48564. this._isInitialized = true;
  48565. }
  48566. };
  48567. SoundTrack.prototype.dispose = function () {
  48568. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48569. if (this._connectedAnalyser) {
  48570. this._connectedAnalyser.stopDebugCanvas();
  48571. }
  48572. while (this.soundCollection.length) {
  48573. this.soundCollection[0].dispose();
  48574. }
  48575. if (this._outputAudioNode) {
  48576. this._outputAudioNode.disconnect();
  48577. }
  48578. this._outputAudioNode = null;
  48579. }
  48580. };
  48581. SoundTrack.prototype.AddSound = function (sound) {
  48582. if (!this._isInitialized) {
  48583. this._initializeSoundTrackAudioGraph();
  48584. }
  48585. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48586. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48587. }
  48588. if (sound.soundTrackId) {
  48589. if (sound.soundTrackId === -1) {
  48590. this._scene.mainSoundTrack.RemoveSound(sound);
  48591. }
  48592. else {
  48593. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48594. }
  48595. }
  48596. this.soundCollection.push(sound);
  48597. sound.soundTrackId = this.id;
  48598. };
  48599. SoundTrack.prototype.RemoveSound = function (sound) {
  48600. var index = this.soundCollection.indexOf(sound);
  48601. if (index !== -1) {
  48602. this.soundCollection.splice(index, 1);
  48603. }
  48604. };
  48605. SoundTrack.prototype.setVolume = function (newVolume) {
  48606. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48607. this._outputAudioNode.gain.value = newVolume;
  48608. }
  48609. };
  48610. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48611. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48612. for (var i = 0; i < this.soundCollection.length; i++) {
  48613. this.soundCollection[i].switchPanningModelToHRTF();
  48614. }
  48615. }
  48616. };
  48617. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48618. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48619. for (var i = 0; i < this.soundCollection.length; i++) {
  48620. this.soundCollection[i].switchPanningModelToEqualPower();
  48621. }
  48622. }
  48623. };
  48624. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48625. if (this._connectedAnalyser) {
  48626. this._connectedAnalyser.stopDebugCanvas();
  48627. }
  48628. this._connectedAnalyser = analyser;
  48629. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48630. this._outputAudioNode.disconnect();
  48631. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  48632. }
  48633. };
  48634. return SoundTrack;
  48635. }());
  48636. BABYLON.SoundTrack = SoundTrack;
  48637. })(BABYLON || (BABYLON = {}));
  48638. //# sourceMappingURL=babylon.soundtrack.js.map
  48639. var BABYLON;
  48640. (function (BABYLON) {
  48641. var Analyser = /** @class */ (function () {
  48642. function Analyser(scene) {
  48643. this.SMOOTHING = 0.75;
  48644. this.FFT_SIZE = 512;
  48645. this.BARGRAPHAMPLITUDE = 256;
  48646. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  48647. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  48648. this._scene = scene;
  48649. this._audioEngine = BABYLON.Engine.audioEngine;
  48650. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  48651. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  48652. this._webAudioAnalyser.minDecibels = -140;
  48653. this._webAudioAnalyser.maxDecibels = 0;
  48654. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48655. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48656. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  48657. }
  48658. }
  48659. Analyser.prototype.getFrequencyBinCount = function () {
  48660. if (this._audioEngine.canUseWebAudio) {
  48661. return this._webAudioAnalyser.frequencyBinCount;
  48662. }
  48663. else {
  48664. return 0;
  48665. }
  48666. };
  48667. Analyser.prototype.getByteFrequencyData = function () {
  48668. if (this._audioEngine.canUseWebAudio) {
  48669. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48670. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48671. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  48672. }
  48673. return this._byteFreqs;
  48674. };
  48675. Analyser.prototype.getByteTimeDomainData = function () {
  48676. if (this._audioEngine.canUseWebAudio) {
  48677. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48678. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48679. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  48680. }
  48681. return this._byteTime;
  48682. };
  48683. Analyser.prototype.getFloatFrequencyData = function () {
  48684. if (this._audioEngine.canUseWebAudio) {
  48685. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48686. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48687. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  48688. }
  48689. return this._floatFreqs;
  48690. };
  48691. Analyser.prototype.drawDebugCanvas = function () {
  48692. var _this = this;
  48693. if (this._audioEngine.canUseWebAudio) {
  48694. if (!this._debugCanvas) {
  48695. this._debugCanvas = document.createElement("canvas");
  48696. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  48697. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  48698. this._debugCanvas.style.position = "absolute";
  48699. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  48700. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  48701. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  48702. document.body.appendChild(this._debugCanvas);
  48703. this._registerFunc = function () {
  48704. _this.drawDebugCanvas();
  48705. };
  48706. this._scene.registerBeforeRender(this._registerFunc);
  48707. }
  48708. if (this._registerFunc && this._debugCanvasContext) {
  48709. var workingArray = this.getByteFrequencyData();
  48710. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  48711. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  48712. // Draw the frequency domain chart.
  48713. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  48714. var value = workingArray[i];
  48715. var percent = value / this.BARGRAPHAMPLITUDE;
  48716. var height = this.DEBUGCANVASSIZE.height * percent;
  48717. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  48718. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  48719. var hue = i / this.getFrequencyBinCount() * 360;
  48720. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  48721. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  48722. }
  48723. }
  48724. }
  48725. };
  48726. Analyser.prototype.stopDebugCanvas = function () {
  48727. if (this._debugCanvas) {
  48728. if (this._registerFunc) {
  48729. this._scene.unregisterBeforeRender(this._registerFunc);
  48730. this._registerFunc = null;
  48731. }
  48732. document.body.removeChild(this._debugCanvas);
  48733. this._debugCanvas = null;
  48734. this._debugCanvasContext = null;
  48735. }
  48736. };
  48737. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  48738. if (this._audioEngine.canUseWebAudio) {
  48739. inputAudioNode.connect(this._webAudioAnalyser);
  48740. this._webAudioAnalyser.connect(outputAudioNode);
  48741. }
  48742. };
  48743. Analyser.prototype.dispose = function () {
  48744. if (this._audioEngine.canUseWebAudio) {
  48745. this._webAudioAnalyser.disconnect();
  48746. }
  48747. };
  48748. return Analyser;
  48749. }());
  48750. BABYLON.Analyser = Analyser;
  48751. })(BABYLON || (BABYLON = {}));
  48752. //# sourceMappingURL=babylon.analyser.js.map
  48753. var BABYLON;
  48754. (function (BABYLON) {
  48755. var CubeTexture = /** @class */ (function (_super) {
  48756. __extends(CubeTexture, _super);
  48757. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  48758. if (extensions === void 0) { extensions = null; }
  48759. if (noMipmap === void 0) { noMipmap = false; }
  48760. if (files === void 0) { files = null; }
  48761. if (onLoad === void 0) { onLoad = null; }
  48762. if (onError === void 0) { onError = null; }
  48763. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  48764. if (prefiltered === void 0) { prefiltered = false; }
  48765. if (forcedExtension === void 0) { forcedExtension = null; }
  48766. var _this = _super.call(this, scene) || this;
  48767. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48768. _this.name = rootUrl;
  48769. _this.url = rootUrl;
  48770. _this._noMipmap = noMipmap;
  48771. _this.hasAlpha = false;
  48772. _this._format = format;
  48773. _this._prefiltered = prefiltered;
  48774. _this.isCube = true;
  48775. _this._textureMatrix = BABYLON.Matrix.Identity();
  48776. if (prefiltered) {
  48777. _this.gammaSpace = false;
  48778. }
  48779. if (!rootUrl && !files) {
  48780. return _this;
  48781. }
  48782. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  48783. if (!files) {
  48784. if (!extensions) {
  48785. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  48786. }
  48787. files = [];
  48788. for (var index = 0; index < extensions.length; index++) {
  48789. files.push(rootUrl + extensions[index]);
  48790. }
  48791. _this._extensions = extensions;
  48792. }
  48793. _this._files = files;
  48794. if (!_this._texture) {
  48795. if (!scene.useDelayedTextureLoading) {
  48796. if (prefiltered) {
  48797. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  48798. }
  48799. else {
  48800. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  48801. }
  48802. }
  48803. else {
  48804. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48805. }
  48806. }
  48807. else if (onLoad) {
  48808. if (_this._texture.isReady) {
  48809. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  48810. }
  48811. else {
  48812. _this._texture.onLoadedObservable.add(onLoad);
  48813. }
  48814. }
  48815. return _this;
  48816. }
  48817. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  48818. return new CubeTexture("", scene, null, noMipmap, files);
  48819. };
  48820. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  48821. if (forcedExtension === void 0) { forcedExtension = null; }
  48822. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  48823. };
  48824. // Methods
  48825. CubeTexture.prototype.delayLoad = function () {
  48826. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48827. return;
  48828. }
  48829. var scene = this.getScene();
  48830. if (!scene) {
  48831. return;
  48832. }
  48833. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  48834. this._texture = this._getFromCache(this.url, this._noMipmap);
  48835. if (!this._texture) {
  48836. if (this._prefiltered) {
  48837. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  48838. }
  48839. else {
  48840. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  48841. }
  48842. }
  48843. };
  48844. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  48845. return this._textureMatrix;
  48846. };
  48847. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  48848. this._textureMatrix = value;
  48849. };
  48850. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  48851. var texture = BABYLON.SerializationHelper.Parse(function () {
  48852. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  48853. }, parsedTexture, scene);
  48854. // Animations
  48855. if (parsedTexture.animations) {
  48856. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  48857. var parsedAnimation = parsedTexture.animations[animationIndex];
  48858. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48859. }
  48860. }
  48861. return texture;
  48862. };
  48863. CubeTexture.prototype.clone = function () {
  48864. var _this = this;
  48865. return BABYLON.SerializationHelper.Clone(function () {
  48866. var scene = _this.getScene();
  48867. if (!scene) {
  48868. return _this;
  48869. }
  48870. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  48871. }, this);
  48872. };
  48873. return CubeTexture;
  48874. }(BABYLON.BaseTexture));
  48875. BABYLON.CubeTexture = CubeTexture;
  48876. })(BABYLON || (BABYLON = {}));
  48877. //# sourceMappingURL=babylon.cubeTexture.js.map
  48878. var BABYLON;
  48879. (function (BABYLON) {
  48880. var RenderTargetTexture = /** @class */ (function (_super) {
  48881. __extends(RenderTargetTexture, _super);
  48882. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  48883. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  48884. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48885. if (isCube === void 0) { isCube = false; }
  48886. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48887. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  48888. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  48889. if (isMulti === void 0) { isMulti = false; }
  48890. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  48891. _this.isCube = isCube;
  48892. /**
  48893. * Use this list to define the list of mesh you want to render.
  48894. */
  48895. _this.renderList = new Array();
  48896. _this.renderParticles = true;
  48897. _this.renderSprites = false;
  48898. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  48899. _this.ignoreCameraViewport = false;
  48900. // Events
  48901. /**
  48902. * An event triggered when the texture is unbind.
  48903. * @type {BABYLON.Observable}
  48904. */
  48905. _this.onBeforeBindObservable = new BABYLON.Observable();
  48906. /**
  48907. * An event triggered when the texture is unbind.
  48908. * @type {BABYLON.Observable}
  48909. */
  48910. _this.onAfterUnbindObservable = new BABYLON.Observable();
  48911. /**
  48912. * An event triggered before rendering the texture
  48913. * @type {BABYLON.Observable}
  48914. */
  48915. _this.onBeforeRenderObservable = new BABYLON.Observable();
  48916. /**
  48917. * An event triggered after rendering the texture
  48918. * @type {BABYLON.Observable}
  48919. */
  48920. _this.onAfterRenderObservable = new BABYLON.Observable();
  48921. /**
  48922. * An event triggered after the texture clear
  48923. * @type {BABYLON.Observable}
  48924. */
  48925. _this.onClearObservable = new BABYLON.Observable();
  48926. _this._currentRefreshId = -1;
  48927. _this._refreshRate = 1;
  48928. _this._samples = 1;
  48929. scene = _this.getScene();
  48930. if (!scene) {
  48931. return _this;
  48932. }
  48933. _this.name = name;
  48934. _this.isRenderTarget = true;
  48935. _this._size = size;
  48936. _this._generateMipMaps = generateMipMaps ? true : false;
  48937. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  48938. // Rendering groups
  48939. _this._renderingManager = new BABYLON.RenderingManager(scene);
  48940. if (isMulti) {
  48941. return _this;
  48942. }
  48943. _this._renderTargetOptions = {
  48944. generateMipMaps: generateMipMaps,
  48945. type: type,
  48946. samplingMode: samplingMode,
  48947. generateDepthBuffer: generateDepthBuffer,
  48948. generateStencilBuffer: generateStencilBuffer
  48949. };
  48950. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  48951. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48952. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48953. }
  48954. if (isCube) {
  48955. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  48956. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  48957. _this._textureMatrix = BABYLON.Matrix.Identity();
  48958. }
  48959. else {
  48960. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  48961. }
  48962. return _this;
  48963. }
  48964. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  48965. get: function () {
  48966. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  48967. },
  48968. enumerable: true,
  48969. configurable: true
  48970. });
  48971. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  48972. get: function () {
  48973. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  48974. },
  48975. enumerable: true,
  48976. configurable: true
  48977. });
  48978. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  48979. get: function () {
  48980. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  48981. },
  48982. enumerable: true,
  48983. configurable: true
  48984. });
  48985. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  48986. set: function (callback) {
  48987. if (this._onAfterUnbindObserver) {
  48988. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  48989. }
  48990. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  48991. },
  48992. enumerable: true,
  48993. configurable: true
  48994. });
  48995. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  48996. set: function (callback) {
  48997. if (this._onBeforeRenderObserver) {
  48998. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48999. }
  49000. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49001. },
  49002. enumerable: true,
  49003. configurable: true
  49004. });
  49005. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49006. set: function (callback) {
  49007. if (this._onAfterRenderObserver) {
  49008. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49009. }
  49010. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49011. },
  49012. enumerable: true,
  49013. configurable: true
  49014. });
  49015. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49016. set: function (callback) {
  49017. if (this._onClearObserver) {
  49018. this.onClearObservable.remove(this._onClearObserver);
  49019. }
  49020. this._onClearObserver = this.onClearObservable.add(callback);
  49021. },
  49022. enumerable: true,
  49023. configurable: true
  49024. });
  49025. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49026. get: function () {
  49027. return this._renderTargetOptions;
  49028. },
  49029. enumerable: true,
  49030. configurable: true
  49031. });
  49032. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49033. get: function () {
  49034. return this._samples;
  49035. },
  49036. set: function (value) {
  49037. if (this._samples === value) {
  49038. return;
  49039. }
  49040. var scene = this.getScene();
  49041. if (!scene) {
  49042. return;
  49043. }
  49044. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49045. },
  49046. enumerable: true,
  49047. configurable: true
  49048. });
  49049. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49050. this._currentRefreshId = -1;
  49051. };
  49052. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49053. get: function () {
  49054. return this._refreshRate;
  49055. },
  49056. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49057. set: function (value) {
  49058. this._refreshRate = value;
  49059. this.resetRefreshCounter();
  49060. },
  49061. enumerable: true,
  49062. configurable: true
  49063. });
  49064. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49065. if (!this._postProcessManager) {
  49066. var scene = this.getScene();
  49067. if (!scene) {
  49068. return;
  49069. }
  49070. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49071. this._postProcesses = new Array();
  49072. }
  49073. this._postProcesses.push(postProcess);
  49074. this._postProcesses[0].autoClear = false;
  49075. };
  49076. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49077. if (!this._postProcesses) {
  49078. return;
  49079. }
  49080. if (dispose) {
  49081. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49082. var postProcess = _a[_i];
  49083. postProcess.dispose();
  49084. }
  49085. }
  49086. this._postProcesses = [];
  49087. };
  49088. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49089. if (!this._postProcesses) {
  49090. return;
  49091. }
  49092. var index = this._postProcesses.indexOf(postProcess);
  49093. if (index === -1) {
  49094. return;
  49095. }
  49096. this._postProcesses.splice(index, 1);
  49097. if (this._postProcesses.length > 0) {
  49098. this._postProcesses[0].autoClear = false;
  49099. }
  49100. };
  49101. RenderTargetTexture.prototype._shouldRender = function () {
  49102. if (this._currentRefreshId === -1) {
  49103. this._currentRefreshId = 1;
  49104. return true;
  49105. }
  49106. if (this.refreshRate === this._currentRefreshId) {
  49107. this._currentRefreshId = 1;
  49108. return true;
  49109. }
  49110. this._currentRefreshId++;
  49111. return false;
  49112. };
  49113. RenderTargetTexture.prototype.getRenderSize = function () {
  49114. return this._size;
  49115. };
  49116. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49117. get: function () {
  49118. return true;
  49119. },
  49120. enumerable: true,
  49121. configurable: true
  49122. });
  49123. RenderTargetTexture.prototype.scale = function (ratio) {
  49124. var newSize = this._size * ratio;
  49125. this.resize(newSize);
  49126. };
  49127. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49128. if (this.isCube) {
  49129. return this._textureMatrix;
  49130. }
  49131. return _super.prototype.getReflectionTextureMatrix.call(this);
  49132. };
  49133. RenderTargetTexture.prototype.resize = function (size) {
  49134. this.releaseInternalTexture();
  49135. var scene = this.getScene();
  49136. if (!scene) {
  49137. return;
  49138. }
  49139. if (this.isCube) {
  49140. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  49141. }
  49142. else {
  49143. this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  49144. }
  49145. this._size = size;
  49146. };
  49147. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49148. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49149. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49150. var scene = this.getScene();
  49151. if (!scene) {
  49152. return;
  49153. }
  49154. var engine = scene.getEngine();
  49155. if (this.useCameraPostProcesses !== undefined) {
  49156. useCameraPostProcess = this.useCameraPostProcesses;
  49157. }
  49158. if (this._waitingRenderList) {
  49159. this.renderList = [];
  49160. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49161. var id = this._waitingRenderList[index];
  49162. var mesh_1 = scene.getMeshByID(id);
  49163. if (mesh_1) {
  49164. this.renderList.push(mesh_1);
  49165. }
  49166. }
  49167. delete this._waitingRenderList;
  49168. }
  49169. // Is predicate defined?
  49170. if (this.renderListPredicate) {
  49171. if (this.renderList) {
  49172. this.renderList.splice(0); // Clear previous renderList
  49173. }
  49174. else {
  49175. this.renderList = [];
  49176. }
  49177. var scene = this.getScene();
  49178. if (!scene) {
  49179. return;
  49180. }
  49181. var sceneMeshes = scene.meshes;
  49182. for (var index = 0; index < sceneMeshes.length; index++) {
  49183. var mesh = sceneMeshes[index];
  49184. if (this.renderListPredicate(mesh)) {
  49185. this.renderList.push(mesh);
  49186. }
  49187. }
  49188. }
  49189. this.onBeforeBindObservable.notifyObservers(this);
  49190. // Set custom projection.
  49191. // Needs to be before binding to prevent changing the aspect ratio.
  49192. var camera;
  49193. if (this.activeCamera) {
  49194. camera = this.activeCamera;
  49195. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  49196. if (this.activeCamera !== scene.activeCamera) {
  49197. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49198. }
  49199. }
  49200. else {
  49201. camera = scene.activeCamera;
  49202. if (camera) {
  49203. engine.setViewport(camera.viewport, this._size, this._size);
  49204. }
  49205. }
  49206. // Prepare renderingManager
  49207. this._renderingManager.reset();
  49208. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49209. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49210. var sceneRenderId = scene.getRenderId();
  49211. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49212. var mesh = currentRenderList[meshIndex];
  49213. if (mesh) {
  49214. if (!mesh.isReady()) {
  49215. // Reset _currentRefreshId
  49216. this.resetRefreshCounter();
  49217. continue;
  49218. }
  49219. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49220. var isMasked = void 0;
  49221. if (!this.renderList && camera) {
  49222. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49223. }
  49224. else {
  49225. isMasked = false;
  49226. }
  49227. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49228. mesh._activate(sceneRenderId);
  49229. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49230. var subMesh = mesh.subMeshes[subIndex];
  49231. scene._activeIndices.addCount(subMesh.indexCount, false);
  49232. this._renderingManager.dispatch(subMesh);
  49233. }
  49234. }
  49235. }
  49236. }
  49237. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49238. var particleSystem = scene.particleSystems[particleIndex];
  49239. var emitter = particleSystem.emitter;
  49240. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49241. continue;
  49242. }
  49243. if (currentRenderList.indexOf(emitter) >= 0) {
  49244. this._renderingManager.dispatchParticles(particleSystem);
  49245. }
  49246. }
  49247. if (this.isCube) {
  49248. for (var face = 0; face < 6; face++) {
  49249. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49250. scene.incrementRenderId();
  49251. scene.resetCachedMaterial();
  49252. }
  49253. }
  49254. else {
  49255. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49256. }
  49257. this.onAfterUnbindObservable.notifyObservers(this);
  49258. if (scene.activeCamera) {
  49259. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49260. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49261. }
  49262. engine.setViewport(scene.activeCamera.viewport);
  49263. }
  49264. scene.resetCachedMaterial();
  49265. };
  49266. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49267. var _this = this;
  49268. var scene = this.getScene();
  49269. if (!scene) {
  49270. return;
  49271. }
  49272. var engine = scene.getEngine();
  49273. if (!this._texture) {
  49274. return;
  49275. }
  49276. // Bind
  49277. if (this._postProcessManager) {
  49278. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49279. }
  49280. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49281. if (this._texture) {
  49282. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49283. }
  49284. }
  49285. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49286. // Clear
  49287. if (this.onClearObservable.hasObservers()) {
  49288. this.onClearObservable.notifyObservers(engine);
  49289. }
  49290. else {
  49291. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49292. }
  49293. if (!this._doNotChangeAspectRatio) {
  49294. scene.updateTransformMatrix(true);
  49295. }
  49296. // Render
  49297. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49298. if (this._postProcessManager) {
  49299. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49300. }
  49301. else if (useCameraPostProcess) {
  49302. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49303. }
  49304. if (!this._doNotChangeAspectRatio) {
  49305. scene.updateTransformMatrix(true);
  49306. }
  49307. // Dump ?
  49308. if (dumpForDebug) {
  49309. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  49310. }
  49311. // Unbind
  49312. if (!this.isCube || faceIndex === 5) {
  49313. if (this.isCube) {
  49314. if (faceIndex === 5) {
  49315. engine.generateMipMapsForCubemap(this._texture);
  49316. }
  49317. }
  49318. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49319. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49320. });
  49321. }
  49322. else {
  49323. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49324. }
  49325. };
  49326. /**
  49327. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49328. * This allowed control for front to back rendering or reversly depending of the special needs.
  49329. *
  49330. * @param renderingGroupId The rendering group id corresponding to its index
  49331. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49332. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49333. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49334. */
  49335. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49336. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49337. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49338. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49339. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49340. };
  49341. /**
  49342. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49343. *
  49344. * @param renderingGroupId The rendering group id corresponding to its index
  49345. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49346. */
  49347. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49348. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49349. };
  49350. RenderTargetTexture.prototype.clone = function () {
  49351. var textureSize = this.getSize();
  49352. 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);
  49353. // Base texture
  49354. newTexture.hasAlpha = this.hasAlpha;
  49355. newTexture.level = this.level;
  49356. // RenderTarget Texture
  49357. newTexture.coordinatesMode = this.coordinatesMode;
  49358. if (this.renderList) {
  49359. newTexture.renderList = this.renderList.slice(0);
  49360. }
  49361. return newTexture;
  49362. };
  49363. RenderTargetTexture.prototype.serialize = function () {
  49364. if (!this.name) {
  49365. return null;
  49366. }
  49367. var serializationObject = _super.prototype.serialize.call(this);
  49368. serializationObject.renderTargetSize = this.getRenderSize();
  49369. serializationObject.renderList = [];
  49370. if (this.renderList) {
  49371. for (var index = 0; index < this.renderList.length; index++) {
  49372. serializationObject.renderList.push(this.renderList[index].id);
  49373. }
  49374. }
  49375. return serializationObject;
  49376. };
  49377. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49378. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49379. var objBuffer = this.getInternalTexture();
  49380. var scene = this.getScene();
  49381. if (objBuffer && scene) {
  49382. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49383. }
  49384. };
  49385. RenderTargetTexture.prototype.dispose = function () {
  49386. if (this._postProcessManager) {
  49387. this._postProcessManager.dispose();
  49388. this._postProcessManager = null;
  49389. }
  49390. this.clearPostProcesses(true);
  49391. this.renderList = null;
  49392. // Remove from custom render targets
  49393. var scene = this.getScene();
  49394. if (!scene) {
  49395. return;
  49396. }
  49397. var index = scene.customRenderTargets.indexOf(this);
  49398. if (index >= 0) {
  49399. scene.customRenderTargets.splice(index, 1);
  49400. }
  49401. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49402. var camera = _a[_i];
  49403. index = camera.customRenderTargets.indexOf(this);
  49404. if (index >= 0) {
  49405. camera.customRenderTargets.splice(index, 1);
  49406. }
  49407. }
  49408. _super.prototype.dispose.call(this);
  49409. };
  49410. RenderTargetTexture.prototype._rebuild = function () {
  49411. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49412. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49413. }
  49414. if (this._postProcessManager) {
  49415. this._postProcessManager._rebuild();
  49416. }
  49417. };
  49418. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49419. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49420. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49421. return RenderTargetTexture;
  49422. }(BABYLON.Texture));
  49423. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49424. })(BABYLON || (BABYLON = {}));
  49425. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49426. var BABYLON;
  49427. (function (BABYLON) {
  49428. ;
  49429. var MultiRenderTarget = /** @class */ (function (_super) {
  49430. __extends(MultiRenderTarget, _super);
  49431. function MultiRenderTarget(name, size, count, scene, options) {
  49432. var _this = this;
  49433. options = options || {};
  49434. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49435. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49436. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49437. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49438. _this._engine = scene.getEngine();
  49439. if (!_this.isSupported) {
  49440. _this.dispose();
  49441. return;
  49442. }
  49443. var types = [];
  49444. var samplingModes = [];
  49445. for (var i = 0; i < count; i++) {
  49446. if (options.types && options.types[i]) {
  49447. types.push(options.types[i]);
  49448. }
  49449. else {
  49450. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49451. }
  49452. if (options.samplingModes && options.samplingModes[i]) {
  49453. samplingModes.push(options.samplingModes[i]);
  49454. }
  49455. else {
  49456. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49457. }
  49458. }
  49459. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49460. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49461. _this._count = count;
  49462. _this._size = size;
  49463. _this._multiRenderTargetOptions = {
  49464. samplingModes: samplingModes,
  49465. generateMipMaps: generateMipMaps,
  49466. generateDepthBuffer: generateDepthBuffer,
  49467. generateStencilBuffer: generateStencilBuffer,
  49468. generateDepthTexture: generateDepthTexture,
  49469. types: types,
  49470. textureCount: count
  49471. };
  49472. _this._createInternalTextures();
  49473. _this._createTextures();
  49474. return _this;
  49475. }
  49476. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49477. get: function () {
  49478. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49479. },
  49480. enumerable: true,
  49481. configurable: true
  49482. });
  49483. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49484. get: function () {
  49485. return this._textures;
  49486. },
  49487. enumerable: true,
  49488. configurable: true
  49489. });
  49490. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49491. get: function () {
  49492. return this._textures[this._textures.length - 1];
  49493. },
  49494. enumerable: true,
  49495. configurable: true
  49496. });
  49497. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49498. set: function (wrap) {
  49499. if (this._textures) {
  49500. for (var i = 0; i < this._textures.length; i++) {
  49501. this._textures[i].wrapU = wrap;
  49502. }
  49503. }
  49504. },
  49505. enumerable: true,
  49506. configurable: true
  49507. });
  49508. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49509. set: function (wrap) {
  49510. if (this._textures) {
  49511. for (var i = 0; i < this._textures.length; i++) {
  49512. this._textures[i].wrapV = wrap;
  49513. }
  49514. }
  49515. },
  49516. enumerable: true,
  49517. configurable: true
  49518. });
  49519. MultiRenderTarget.prototype._rebuild = function () {
  49520. this.releaseInternalTextures();
  49521. this._createInternalTextures();
  49522. for (var i = 0; i < this._internalTextures.length; i++) {
  49523. var texture = this._textures[i];
  49524. texture._texture = this._internalTextures[i];
  49525. }
  49526. // Keeps references to frame buffer and stencil/depth buffer
  49527. this._texture = this._internalTextures[0];
  49528. };
  49529. MultiRenderTarget.prototype._createInternalTextures = function () {
  49530. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49531. };
  49532. MultiRenderTarget.prototype._createTextures = function () {
  49533. this._textures = [];
  49534. for (var i = 0; i < this._internalTextures.length; i++) {
  49535. var texture = new BABYLON.Texture(null, this.getScene());
  49536. texture._texture = this._internalTextures[i];
  49537. this._textures.push(texture);
  49538. }
  49539. // Keeps references to frame buffer and stencil/depth buffer
  49540. this._texture = this._internalTextures[0];
  49541. };
  49542. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49543. get: function () {
  49544. return this._samples;
  49545. },
  49546. set: function (value) {
  49547. if (this._samples === value) {
  49548. return;
  49549. }
  49550. for (var i = 0; i < this._internalTextures.length; i++) {
  49551. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49552. }
  49553. },
  49554. enumerable: true,
  49555. configurable: true
  49556. });
  49557. MultiRenderTarget.prototype.resize = function (size) {
  49558. this.releaseInternalTextures();
  49559. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49560. this._createInternalTextures();
  49561. };
  49562. MultiRenderTarget.prototype.dispose = function () {
  49563. this.releaseInternalTextures();
  49564. _super.prototype.dispose.call(this);
  49565. };
  49566. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49567. if (!this._internalTextures) {
  49568. return;
  49569. }
  49570. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49571. if (this._internalTextures[i] !== undefined) {
  49572. this._internalTextures[i].dispose();
  49573. this._internalTextures.splice(i, 1);
  49574. }
  49575. }
  49576. };
  49577. return MultiRenderTarget;
  49578. }(BABYLON.RenderTargetTexture));
  49579. BABYLON.MultiRenderTarget = MultiRenderTarget;
  49580. })(BABYLON || (BABYLON = {}));
  49581. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  49582. /// <reference path="babylon.renderTargetTexture.ts" />
  49583. var BABYLON;
  49584. (function (BABYLON) {
  49585. var MirrorTexture = /** @class */ (function (_super) {
  49586. __extends(MirrorTexture, _super);
  49587. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  49588. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49589. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49590. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49591. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  49592. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  49593. _this._transformMatrix = BABYLON.Matrix.Zero();
  49594. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  49595. _this._blurKernelX = 0;
  49596. _this._blurKernelY = 0;
  49597. _this._blurRatio = 1.0;
  49598. _this.ignoreCameraViewport = true;
  49599. _this.onBeforeRenderObservable.add(function () {
  49600. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  49601. _this._savedViewMatrix = scene.getViewMatrix();
  49602. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  49603. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  49604. scene.clipPlane = _this.mirrorPlane;
  49605. scene.getEngine().cullBackFaces = false;
  49606. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  49607. });
  49608. _this.onAfterRenderObservable.add(function () {
  49609. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  49610. scene.getEngine().cullBackFaces = true;
  49611. scene._mirroredCameraPosition = null;
  49612. delete scene.clipPlane;
  49613. });
  49614. return _this;
  49615. }
  49616. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  49617. get: function () {
  49618. return this._blurRatio;
  49619. },
  49620. set: function (value) {
  49621. if (this._blurRatio === value) {
  49622. return;
  49623. }
  49624. this._blurRatio = value;
  49625. this._preparePostProcesses();
  49626. },
  49627. enumerable: true,
  49628. configurable: true
  49629. });
  49630. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  49631. set: function (value) {
  49632. this.blurKernelX = value;
  49633. this.blurKernelY = value;
  49634. },
  49635. enumerable: true,
  49636. configurable: true
  49637. });
  49638. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  49639. get: function () {
  49640. return this._blurKernelX;
  49641. },
  49642. set: function (value) {
  49643. if (this._blurKernelX === value) {
  49644. return;
  49645. }
  49646. this._blurKernelX = value;
  49647. this._preparePostProcesses();
  49648. },
  49649. enumerable: true,
  49650. configurable: true
  49651. });
  49652. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  49653. get: function () {
  49654. return this._blurKernelY;
  49655. },
  49656. set: function (value) {
  49657. if (this._blurKernelY === value) {
  49658. return;
  49659. }
  49660. this._blurKernelY = value;
  49661. this._preparePostProcesses();
  49662. },
  49663. enumerable: true,
  49664. configurable: true
  49665. });
  49666. MirrorTexture.prototype._preparePostProcesses = function () {
  49667. this.clearPostProcesses(true);
  49668. if (this._blurKernelX && this._blurKernelY) {
  49669. var engine = this.getScene().getEngine();
  49670. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49671. 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);
  49672. this._blurX.autoClear = false;
  49673. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  49674. this._blurX.outputTexture = this._texture;
  49675. }
  49676. else {
  49677. this._blurX.alwaysForcePOT = true;
  49678. }
  49679. 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);
  49680. this._blurY.autoClear = false;
  49681. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  49682. this.addPostProcess(this._blurX);
  49683. this.addPostProcess(this._blurY);
  49684. }
  49685. };
  49686. MirrorTexture.prototype.clone = function () {
  49687. var scene = this.getScene();
  49688. if (!scene) {
  49689. return this;
  49690. }
  49691. var textureSize = this.getSize();
  49692. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  49693. // Base texture
  49694. newTexture.hasAlpha = this.hasAlpha;
  49695. newTexture.level = this.level;
  49696. // Mirror Texture
  49697. newTexture.mirrorPlane = this.mirrorPlane.clone();
  49698. if (this.renderList) {
  49699. newTexture.renderList = this.renderList.slice(0);
  49700. }
  49701. return newTexture;
  49702. };
  49703. MirrorTexture.prototype.serialize = function () {
  49704. if (!this.name) {
  49705. return null;
  49706. }
  49707. var serializationObject = _super.prototype.serialize.call(this);
  49708. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  49709. return serializationObject;
  49710. };
  49711. return MirrorTexture;
  49712. }(BABYLON.RenderTargetTexture));
  49713. BABYLON.MirrorTexture = MirrorTexture;
  49714. })(BABYLON || (BABYLON = {}));
  49715. //# sourceMappingURL=babylon.mirrorTexture.js.map
  49716. /// <reference path="babylon.renderTargetTexture.ts" />
  49717. var BABYLON;
  49718. (function (BABYLON) {
  49719. /**
  49720. * Creates a refraction texture used by refraction channel of the standard material.
  49721. * @param name the texture name
  49722. * @param size size of the underlying texture
  49723. * @param scene root scene
  49724. */
  49725. var RefractionTexture = /** @class */ (function (_super) {
  49726. __extends(RefractionTexture, _super);
  49727. function RefractionTexture(name, size, scene, generateMipMaps) {
  49728. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  49729. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  49730. _this.depth = 2.0;
  49731. _this.onBeforeRenderObservable.add(function () {
  49732. scene.clipPlane = _this.refractionPlane;
  49733. });
  49734. _this.onAfterRenderObservable.add(function () {
  49735. delete scene.clipPlane;
  49736. });
  49737. return _this;
  49738. }
  49739. RefractionTexture.prototype.clone = function () {
  49740. var scene = this.getScene();
  49741. if (!scene) {
  49742. return this;
  49743. }
  49744. var textureSize = this.getSize();
  49745. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  49746. // Base texture
  49747. newTexture.hasAlpha = this.hasAlpha;
  49748. newTexture.level = this.level;
  49749. // Refraction Texture
  49750. newTexture.refractionPlane = this.refractionPlane.clone();
  49751. if (this.renderList) {
  49752. newTexture.renderList = this.renderList.slice(0);
  49753. }
  49754. newTexture.depth = this.depth;
  49755. return newTexture;
  49756. };
  49757. RefractionTexture.prototype.serialize = function () {
  49758. if (!this.name) {
  49759. return null;
  49760. }
  49761. var serializationObject = _super.prototype.serialize.call(this);
  49762. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  49763. serializationObject.depth = this.depth;
  49764. return serializationObject;
  49765. };
  49766. return RefractionTexture;
  49767. }(BABYLON.RenderTargetTexture));
  49768. BABYLON.RefractionTexture = RefractionTexture;
  49769. })(BABYLON || (BABYLON = {}));
  49770. //# sourceMappingURL=babylon.refractionTexture.js.map
  49771. /// <reference path="babylon.texture.ts" />
  49772. var BABYLON;
  49773. (function (BABYLON) {
  49774. var DynamicTexture = /** @class */ (function (_super) {
  49775. __extends(DynamicTexture, _super);
  49776. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  49777. if (scene === void 0) { scene = null; }
  49778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49779. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49780. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  49781. _this.name = name;
  49782. _this._engine = _this.getScene().getEngine();
  49783. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49784. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49785. _this._generateMipMaps = generateMipMaps;
  49786. if (options.getContext) {
  49787. _this._canvas = options;
  49788. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49789. }
  49790. else {
  49791. _this._canvas = document.createElement("canvas");
  49792. if (options.width) {
  49793. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49794. }
  49795. else {
  49796. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  49797. }
  49798. }
  49799. var textureSize = _this.getSize();
  49800. _this._canvas.width = textureSize.width;
  49801. _this._canvas.height = textureSize.height;
  49802. _this._context = _this._canvas.getContext("2d");
  49803. return _this;
  49804. }
  49805. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  49806. get: function () {
  49807. return true;
  49808. },
  49809. enumerable: true,
  49810. configurable: true
  49811. });
  49812. DynamicTexture.prototype._recreate = function (textureSize) {
  49813. this._canvas.width = textureSize.width;
  49814. this._canvas.height = textureSize.height;
  49815. this.releaseInternalTexture();
  49816. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  49817. };
  49818. DynamicTexture.prototype.scale = function (ratio) {
  49819. var textureSize = this.getSize();
  49820. textureSize.width *= ratio;
  49821. textureSize.height *= ratio;
  49822. this._recreate(textureSize);
  49823. };
  49824. DynamicTexture.prototype.scaleTo = function (width, height) {
  49825. var textureSize = this.getSize();
  49826. textureSize.width = width;
  49827. textureSize.height = height;
  49828. this._recreate(textureSize);
  49829. };
  49830. DynamicTexture.prototype.getContext = function () {
  49831. return this._context;
  49832. };
  49833. DynamicTexture.prototype.clear = function () {
  49834. var size = this.getSize();
  49835. this._context.fillRect(0, 0, size.width, size.height);
  49836. };
  49837. DynamicTexture.prototype.update = function (invertY) {
  49838. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  49839. };
  49840. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  49841. if (update === void 0) { update = true; }
  49842. var size = this.getSize();
  49843. if (clearColor) {
  49844. this._context.fillStyle = clearColor;
  49845. this._context.fillRect(0, 0, size.width, size.height);
  49846. }
  49847. this._context.font = font;
  49848. if (x === null || x === undefined) {
  49849. var textSize = this._context.measureText(text);
  49850. x = (size.width - textSize.width) / 2;
  49851. }
  49852. if (y === null || y === undefined) {
  49853. var fontSize = parseInt((font.replace(/\D/g, '')));
  49854. ;
  49855. y = (size.height / 2) + (fontSize / 3.65);
  49856. }
  49857. this._context.fillStyle = color;
  49858. this._context.fillText(text, x, y);
  49859. if (update) {
  49860. this.update(invertY);
  49861. }
  49862. };
  49863. DynamicTexture.prototype.clone = function () {
  49864. var scene = this.getScene();
  49865. if (!scene) {
  49866. return this;
  49867. }
  49868. var textureSize = this.getSize();
  49869. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  49870. // Base texture
  49871. newTexture.hasAlpha = this.hasAlpha;
  49872. newTexture.level = this.level;
  49873. // Dynamic Texture
  49874. newTexture.wrapU = this.wrapU;
  49875. newTexture.wrapV = this.wrapV;
  49876. return newTexture;
  49877. };
  49878. DynamicTexture.prototype._rebuild = function () {
  49879. this.update();
  49880. };
  49881. return DynamicTexture;
  49882. }(BABYLON.Texture));
  49883. BABYLON.DynamicTexture = DynamicTexture;
  49884. })(BABYLON || (BABYLON = {}));
  49885. //# sourceMappingURL=babylon.dynamicTexture.js.map
  49886. var BABYLON;
  49887. (function (BABYLON) {
  49888. var VideoTexture = /** @class */ (function (_super) {
  49889. __extends(VideoTexture, _super);
  49890. /**
  49891. * Creates a video texture.
  49892. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  49893. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  49894. * @param {BABYLON.Scene} scene is obviously the current scene.
  49895. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  49896. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  49897. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  49898. */
  49899. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  49900. if (generateMipMaps === void 0) { generateMipMaps = false; }
  49901. if (invertY === void 0) { invertY = false; }
  49902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49903. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  49904. _this._autoLaunch = true;
  49905. var urls = null;
  49906. _this.name = name;
  49907. if (urlsOrVideo instanceof HTMLVideoElement) {
  49908. _this.video = urlsOrVideo;
  49909. }
  49910. else {
  49911. urls = urlsOrVideo;
  49912. _this.video = document.createElement("video");
  49913. _this.video.autoplay = false;
  49914. _this.video.loop = true;
  49915. }
  49916. _this._engine = _this.getScene().getEngine();
  49917. _this._generateMipMaps = generateMipMaps;
  49918. _this._samplingMode = samplingMode;
  49919. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  49920. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49921. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49922. }
  49923. else {
  49924. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49925. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49926. _this._generateMipMaps = false;
  49927. }
  49928. if (urls) {
  49929. _this.video.addEventListener("canplay", function () {
  49930. _this._createTexture();
  49931. });
  49932. urls.forEach(function (url) {
  49933. var source = document.createElement("source");
  49934. source.src = url;
  49935. _this.video.appendChild(source);
  49936. });
  49937. }
  49938. else {
  49939. _this._createTexture();
  49940. }
  49941. _this._lastUpdate = BABYLON.Tools.Now;
  49942. return _this;
  49943. }
  49944. VideoTexture.prototype.__setTextureReady = function () {
  49945. if (this._texture) {
  49946. this._texture.isReady = true;
  49947. }
  49948. };
  49949. VideoTexture.prototype._createTexture = function () {
  49950. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  49951. if (this._autoLaunch) {
  49952. this._autoLaunch = false;
  49953. this.video.play();
  49954. }
  49955. this._setTextureReady = this.__setTextureReady.bind(this);
  49956. this.video.addEventListener("playing", this._setTextureReady);
  49957. };
  49958. VideoTexture.prototype._rebuild = function () {
  49959. this.update();
  49960. };
  49961. VideoTexture.prototype.update = function () {
  49962. var now = BABYLON.Tools.Now;
  49963. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  49964. return false;
  49965. }
  49966. this._lastUpdate = now;
  49967. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  49968. return true;
  49969. };
  49970. VideoTexture.prototype.dispose = function () {
  49971. _super.prototype.dispose.call(this);
  49972. this.video.removeEventListener("playing", this._setTextureReady);
  49973. };
  49974. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  49975. var video = document.createElement("video");
  49976. var constraintsDeviceId;
  49977. if (constraints && constraints.deviceId) {
  49978. constraintsDeviceId = {
  49979. exact: constraints.deviceId
  49980. };
  49981. }
  49982. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  49983. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  49984. if (navigator.getUserMedia) {
  49985. navigator.getUserMedia({
  49986. video: {
  49987. deviceId: constraintsDeviceId,
  49988. width: {
  49989. min: (constraints && constraints.minWidth) || 256,
  49990. max: (constraints && constraints.maxWidth) || 640
  49991. },
  49992. height: {
  49993. min: (constraints && constraints.minHeight) || 256,
  49994. max: (constraints && constraints.maxHeight) || 480
  49995. }
  49996. }
  49997. }, function (stream) {
  49998. if (video.mozSrcObject !== undefined) {
  49999. video.mozSrcObject = stream;
  50000. }
  50001. else {
  50002. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50003. }
  50004. video.play();
  50005. if (onReady) {
  50006. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50007. }
  50008. }, function (e) {
  50009. BABYLON.Tools.Error(e.name);
  50010. });
  50011. }
  50012. };
  50013. return VideoTexture;
  50014. }(BABYLON.Texture));
  50015. BABYLON.VideoTexture = VideoTexture;
  50016. })(BABYLON || (BABYLON = {}));
  50017. //# sourceMappingURL=babylon.videoTexture.js.map
  50018. var BABYLON;
  50019. (function (BABYLON) {
  50020. var RawTexture = /** @class */ (function (_super) {
  50021. __extends(RawTexture, _super);
  50022. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50023. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50024. if (invertY === void 0) { invertY = false; }
  50025. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50026. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50027. _this.format = format;
  50028. _this._engine = scene.getEngine();
  50029. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50030. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50031. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50032. return _this;
  50033. }
  50034. RawTexture.prototype.update = function (data) {
  50035. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50036. };
  50037. // Statics
  50038. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50039. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50040. if (invertY === void 0) { invertY = false; }
  50041. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50042. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50043. };
  50044. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50045. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50046. if (invertY === void 0) { invertY = false; }
  50047. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50048. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50049. };
  50050. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50051. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50052. if (invertY === void 0) { invertY = false; }
  50053. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50054. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50055. };
  50056. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50057. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50058. if (invertY === void 0) { invertY = false; }
  50059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50060. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50061. };
  50062. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50063. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50064. if (invertY === void 0) { invertY = false; }
  50065. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50066. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50067. };
  50068. return RawTexture;
  50069. }(BABYLON.Texture));
  50070. BABYLON.RawTexture = RawTexture;
  50071. })(BABYLON || (BABYLON = {}));
  50072. //# sourceMappingURL=babylon.rawTexture.js.map
  50073. var BABYLON;
  50074. (function (BABYLON) {
  50075. var PostProcess = /** @class */ (function () {
  50076. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50078. if (defines === void 0) { defines = null; }
  50079. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50080. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50081. if (blockCompilation === void 0) { blockCompilation = false; }
  50082. this.name = name;
  50083. this.width = -1;
  50084. this.height = -1;
  50085. this.autoClear = true;
  50086. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50087. /*
  50088. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50089. Can only be used on a single postprocess or on the last one of a chain.
  50090. */
  50091. this.enablePixelPerfectMode = false;
  50092. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50093. this.alwaysForcePOT = false;
  50094. this.samples = 1;
  50095. this.adaptScaleToCurrentViewport = false;
  50096. this._reusable = false;
  50097. this._textures = new BABYLON.SmartArray(2);
  50098. this._currentRenderTextureInd = 0;
  50099. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50100. this._texelSize = BABYLON.Vector2.Zero();
  50101. // Events
  50102. /**
  50103. * An event triggered when the postprocess is activated.
  50104. * @type {BABYLON.Observable}
  50105. */
  50106. this.onActivateObservable = new BABYLON.Observable();
  50107. /**
  50108. * An event triggered when the postprocess changes its size.
  50109. * @type {BABYLON.Observable}
  50110. */
  50111. this.onSizeChangedObservable = new BABYLON.Observable();
  50112. /**
  50113. * An event triggered when the postprocess applies its effect.
  50114. * @type {BABYLON.Observable}
  50115. */
  50116. this.onApplyObservable = new BABYLON.Observable();
  50117. /**
  50118. * An event triggered before rendering the postprocess
  50119. * @type {BABYLON.Observable}
  50120. */
  50121. this.onBeforeRenderObservable = new BABYLON.Observable();
  50122. /**
  50123. * An event triggered after rendering the postprocess
  50124. * @type {BABYLON.Observable}
  50125. */
  50126. this.onAfterRenderObservable = new BABYLON.Observable();
  50127. if (camera != null) {
  50128. this._camera = camera;
  50129. this._scene = camera.getScene();
  50130. camera.attachPostProcess(this);
  50131. this._engine = this._scene.getEngine();
  50132. this._scene.postProcesses.push(this);
  50133. }
  50134. else if (engine) {
  50135. this._engine = engine;
  50136. this._engine.postProcesses.push(this);
  50137. }
  50138. this._options = options;
  50139. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50140. this._reusable = reusable || false;
  50141. this._textureType = textureType;
  50142. this._samplers = samplers || [];
  50143. this._samplers.push("textureSampler");
  50144. this._fragmentUrl = fragmentUrl;
  50145. this._vertexUrl = vertexUrl;
  50146. this._parameters = parameters || [];
  50147. this._parameters.push("scale");
  50148. this._indexParameters = indexParameters;
  50149. if (!blockCompilation) {
  50150. this.updateEffect(defines);
  50151. }
  50152. }
  50153. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50154. set: function (callback) {
  50155. if (this._onActivateObserver) {
  50156. this.onActivateObservable.remove(this._onActivateObserver);
  50157. }
  50158. if (callback) {
  50159. this._onActivateObserver = this.onActivateObservable.add(callback);
  50160. }
  50161. },
  50162. enumerable: true,
  50163. configurable: true
  50164. });
  50165. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50166. set: function (callback) {
  50167. if (this._onSizeChangedObserver) {
  50168. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50169. }
  50170. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50171. },
  50172. enumerable: true,
  50173. configurable: true
  50174. });
  50175. Object.defineProperty(PostProcess.prototype, "onApply", {
  50176. set: function (callback) {
  50177. if (this._onApplyObserver) {
  50178. this.onApplyObservable.remove(this._onApplyObserver);
  50179. }
  50180. this._onApplyObserver = this.onApplyObservable.add(callback);
  50181. },
  50182. enumerable: true,
  50183. configurable: true
  50184. });
  50185. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50186. set: function (callback) {
  50187. if (this._onBeforeRenderObserver) {
  50188. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50189. }
  50190. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50191. },
  50192. enumerable: true,
  50193. configurable: true
  50194. });
  50195. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50196. set: function (callback) {
  50197. if (this._onAfterRenderObserver) {
  50198. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50199. }
  50200. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50201. },
  50202. enumerable: true,
  50203. configurable: true
  50204. });
  50205. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50206. get: function () {
  50207. return this._textures.data[this._currentRenderTextureInd];
  50208. },
  50209. set: function (value) {
  50210. this._forcedOutputTexture = value;
  50211. },
  50212. enumerable: true,
  50213. configurable: true
  50214. });
  50215. PostProcess.prototype.getCamera = function () {
  50216. return this._camera;
  50217. };
  50218. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50219. get: function () {
  50220. if (this._shareOutputWithPostProcess) {
  50221. return this._shareOutputWithPostProcess.texelSize;
  50222. }
  50223. if (this._forcedOutputTexture) {
  50224. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50225. }
  50226. return this._texelSize;
  50227. },
  50228. enumerable: true,
  50229. configurable: true
  50230. });
  50231. PostProcess.prototype.getEngine = function () {
  50232. return this._engine;
  50233. };
  50234. PostProcess.prototype.getEffect = function () {
  50235. return this._effect;
  50236. };
  50237. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50238. this._disposeTextures();
  50239. this._shareOutputWithPostProcess = postProcess;
  50240. return this;
  50241. };
  50242. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50243. if (defines === void 0) { defines = null; }
  50244. if (uniforms === void 0) { uniforms = null; }
  50245. if (samplers === void 0) { samplers = null; }
  50246. 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);
  50247. };
  50248. PostProcess.prototype.isReusable = function () {
  50249. return this._reusable;
  50250. };
  50251. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50252. PostProcess.prototype.markTextureDirty = function () {
  50253. this.width = -1;
  50254. };
  50255. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50256. var _this = this;
  50257. if (sourceTexture === void 0) { sourceTexture = null; }
  50258. camera = camera || this._camera;
  50259. var scene = camera.getScene();
  50260. var engine = scene.getEngine();
  50261. var maxSize = engine.getCaps().maxTextureSize;
  50262. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50263. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50264. var desiredWidth = (this._options.width || requiredWidth);
  50265. var desiredHeight = this._options.height || requiredHeight;
  50266. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50267. if (this.adaptScaleToCurrentViewport) {
  50268. var currentViewport = engine.currentViewport;
  50269. if (currentViewport) {
  50270. desiredWidth *= currentViewport.width;
  50271. desiredHeight *= currentViewport.height;
  50272. }
  50273. }
  50274. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50275. if (!this._options.width) {
  50276. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50277. }
  50278. if (!this._options.height) {
  50279. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50280. }
  50281. }
  50282. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50283. if (this._textures.length > 0) {
  50284. for (var i = 0; i < this._textures.length; i++) {
  50285. this._engine._releaseTexture(this._textures.data[i]);
  50286. }
  50287. this._textures.reset();
  50288. }
  50289. this.width = desiredWidth;
  50290. this.height = desiredHeight;
  50291. var textureSize = { width: this.width, height: this.height };
  50292. var textureOptions = {
  50293. generateMipMaps: false,
  50294. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50295. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50296. samplingMode: this.renderTargetSamplingMode,
  50297. type: this._textureType
  50298. };
  50299. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50300. if (this._reusable) {
  50301. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50302. }
  50303. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50304. this.onSizeChangedObservable.notifyObservers(this);
  50305. }
  50306. this._textures.forEach(function (texture) {
  50307. if (texture.samples !== _this.samples) {
  50308. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50309. }
  50310. });
  50311. }
  50312. var target;
  50313. if (this._shareOutputWithPostProcess) {
  50314. target = this._shareOutputWithPostProcess.outputTexture;
  50315. }
  50316. else if (this._forcedOutputTexture) {
  50317. target = this._forcedOutputTexture;
  50318. this.width = this._forcedOutputTexture.width;
  50319. this.height = this._forcedOutputTexture.height;
  50320. }
  50321. else {
  50322. target = this.outputTexture;
  50323. }
  50324. if (this.enablePixelPerfectMode) {
  50325. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50326. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50327. }
  50328. else {
  50329. this._scaleRatio.copyFromFloats(1, 1);
  50330. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50331. }
  50332. this.onActivateObservable.notifyObservers(camera);
  50333. // Clear
  50334. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50335. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50336. }
  50337. if (this._reusable) {
  50338. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50339. }
  50340. };
  50341. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50342. get: function () {
  50343. return this._effect.isSupported;
  50344. },
  50345. enumerable: true,
  50346. configurable: true
  50347. });
  50348. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50349. get: function () {
  50350. if (this._shareOutputWithPostProcess) {
  50351. return this._shareOutputWithPostProcess.aspectRatio;
  50352. }
  50353. if (this._forcedOutputTexture) {
  50354. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50355. }
  50356. return this.width / this.height;
  50357. },
  50358. enumerable: true,
  50359. configurable: true
  50360. });
  50361. PostProcess.prototype.apply = function () {
  50362. // Check
  50363. if (!this._effect || !this._effect.isReady())
  50364. return null;
  50365. // States
  50366. this._engine.enableEffect(this._effect);
  50367. this._engine.setState(false);
  50368. this._engine.setDepthBuffer(false);
  50369. this._engine.setDepthWrite(false);
  50370. // Alpha
  50371. this._engine.setAlphaMode(this.alphaMode);
  50372. if (this.alphaConstants) {
  50373. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50374. }
  50375. // Texture
  50376. var source;
  50377. if (this._shareOutputWithPostProcess) {
  50378. source = this._shareOutputWithPostProcess.outputTexture;
  50379. }
  50380. else if (this._forcedOutputTexture) {
  50381. source = this._forcedOutputTexture;
  50382. }
  50383. else {
  50384. source = this.outputTexture;
  50385. }
  50386. this._effect._bindTexture("textureSampler", source);
  50387. // Parameters
  50388. this._effect.setVector2("scale", this._scaleRatio);
  50389. this.onApplyObservable.notifyObservers(this._effect);
  50390. return this._effect;
  50391. };
  50392. PostProcess.prototype._disposeTextures = function () {
  50393. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50394. return;
  50395. }
  50396. if (this._textures.length > 0) {
  50397. for (var i = 0; i < this._textures.length; i++) {
  50398. this._engine._releaseTexture(this._textures.data[i]);
  50399. }
  50400. }
  50401. this._textures.dispose();
  50402. };
  50403. PostProcess.prototype.dispose = function (camera) {
  50404. camera = camera || this._camera;
  50405. this._disposeTextures();
  50406. if (this._scene) {
  50407. var index_1 = this._scene.postProcesses.indexOf(this);
  50408. if (index_1 !== -1) {
  50409. this._scene.postProcesses.splice(index_1, 1);
  50410. }
  50411. }
  50412. else {
  50413. var index_2 = this._engine.postProcesses.indexOf(this);
  50414. if (index_2 !== -1) {
  50415. this._engine.postProcesses.splice(index_2, 1);
  50416. }
  50417. }
  50418. if (!camera) {
  50419. return;
  50420. }
  50421. camera.detachPostProcess(this);
  50422. var index = camera._postProcesses.indexOf(this);
  50423. if (index === 0 && camera._postProcesses.length > 0) {
  50424. this._camera._postProcesses[0].markTextureDirty();
  50425. }
  50426. this.onActivateObservable.clear();
  50427. this.onAfterRenderObservable.clear();
  50428. this.onApplyObservable.clear();
  50429. this.onBeforeRenderObservable.clear();
  50430. this.onSizeChangedObservable.clear();
  50431. };
  50432. return PostProcess;
  50433. }());
  50434. BABYLON.PostProcess = PostProcess;
  50435. })(BABYLON || (BABYLON = {}));
  50436. //# sourceMappingURL=babylon.postProcess.js.map
  50437. var BABYLON;
  50438. (function (BABYLON) {
  50439. var PassPostProcess = /** @class */ (function (_super) {
  50440. __extends(PassPostProcess, _super);
  50441. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50442. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50443. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50444. }
  50445. return PassPostProcess;
  50446. }(BABYLON.PostProcess));
  50447. BABYLON.PassPostProcess = PassPostProcess;
  50448. })(BABYLON || (BABYLON = {}));
  50449. //# sourceMappingURL=babylon.passPostProcess.js.map
  50450. var BABYLON;
  50451. (function (BABYLON) {
  50452. var ShadowGenerator = /** @class */ (function () {
  50453. /**
  50454. * Creates a ShadowGenerator object.
  50455. * A ShadowGenerator is the required tool to use the shadows.
  50456. * Each light casting shadows needs to use its own ShadowGenerator.
  50457. * Required parameters :
  50458. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50459. * - `light`: the light object generating the shadows.
  50460. * - `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.
  50461. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50462. */
  50463. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50464. // Members
  50465. this._bias = 0.00005;
  50466. this._blurBoxOffset = 1;
  50467. this._blurScale = 2;
  50468. this._blurKernel = 1;
  50469. this._useKernelBlur = false;
  50470. this._filter = ShadowGenerator.FILTER_NONE;
  50471. this._darkness = 0;
  50472. this._transparencyShadow = false;
  50473. /**
  50474. * Controls the extent to which the shadows fade out at the edge of the frustum
  50475. * Used only by directionals and spots
  50476. */
  50477. this.frustumEdgeFalloff = 0;
  50478. this.forceBackFacesOnly = false;
  50479. this._lightDirection = BABYLON.Vector3.Zero();
  50480. this._viewMatrix = BABYLON.Matrix.Zero();
  50481. this._projectionMatrix = BABYLON.Matrix.Zero();
  50482. this._transformMatrix = BABYLON.Matrix.Zero();
  50483. this._currentFaceIndex = 0;
  50484. this._currentFaceIndexCache = 0;
  50485. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50486. this._mapSize = mapSize;
  50487. this._light = light;
  50488. this._scene = light.getScene();
  50489. light._shadowGenerator = this;
  50490. // Texture type fallback from float to int if not supported.
  50491. var caps = this._scene.getEngine().getCaps();
  50492. if (!useFullFloatFirst) {
  50493. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50494. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50495. }
  50496. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50497. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50498. }
  50499. else {
  50500. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50501. }
  50502. }
  50503. else {
  50504. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50505. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50506. }
  50507. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50508. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50509. }
  50510. else {
  50511. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50512. }
  50513. }
  50514. this._initializeGenerator();
  50515. }
  50516. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50517. // Static
  50518. get: function () {
  50519. return ShadowGenerator._FILTER_NONE;
  50520. },
  50521. enumerable: true,
  50522. configurable: true
  50523. });
  50524. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50525. get: function () {
  50526. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50527. },
  50528. enumerable: true,
  50529. configurable: true
  50530. });
  50531. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50532. get: function () {
  50533. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50534. },
  50535. enumerable: true,
  50536. configurable: true
  50537. });
  50538. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50539. get: function () {
  50540. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50541. },
  50542. enumerable: true,
  50543. configurable: true
  50544. });
  50545. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50546. get: function () {
  50547. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50548. },
  50549. enumerable: true,
  50550. configurable: true
  50551. });
  50552. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50553. get: function () {
  50554. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50555. },
  50556. enumerable: true,
  50557. configurable: true
  50558. });
  50559. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  50560. get: function () {
  50561. return this._bias;
  50562. },
  50563. set: function (bias) {
  50564. this._bias = bias;
  50565. },
  50566. enumerable: true,
  50567. configurable: true
  50568. });
  50569. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  50570. get: function () {
  50571. return this._blurBoxOffset;
  50572. },
  50573. set: function (value) {
  50574. if (this._blurBoxOffset === value) {
  50575. return;
  50576. }
  50577. this._blurBoxOffset = value;
  50578. this._disposeBlurPostProcesses();
  50579. },
  50580. enumerable: true,
  50581. configurable: true
  50582. });
  50583. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  50584. get: function () {
  50585. return this._blurScale;
  50586. },
  50587. set: function (value) {
  50588. if (this._blurScale === value) {
  50589. return;
  50590. }
  50591. this._blurScale = value;
  50592. this._disposeBlurPostProcesses();
  50593. },
  50594. enumerable: true,
  50595. configurable: true
  50596. });
  50597. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  50598. get: function () {
  50599. return this._blurKernel;
  50600. },
  50601. set: function (value) {
  50602. if (this._blurKernel === value) {
  50603. return;
  50604. }
  50605. this._blurKernel = value;
  50606. this._disposeBlurPostProcesses();
  50607. },
  50608. enumerable: true,
  50609. configurable: true
  50610. });
  50611. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  50612. get: function () {
  50613. return this._useKernelBlur;
  50614. },
  50615. set: function (value) {
  50616. if (this._useKernelBlur === value) {
  50617. return;
  50618. }
  50619. this._useKernelBlur = value;
  50620. this._disposeBlurPostProcesses();
  50621. },
  50622. enumerable: true,
  50623. configurable: true
  50624. });
  50625. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  50626. get: function () {
  50627. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  50628. },
  50629. set: function (value) {
  50630. this._depthScale = value;
  50631. },
  50632. enumerable: true,
  50633. configurable: true
  50634. });
  50635. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  50636. get: function () {
  50637. return this._filter;
  50638. },
  50639. set: function (value) {
  50640. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  50641. if (this._light.needCube()) {
  50642. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50643. this.useExponentialShadowMap = true;
  50644. return;
  50645. }
  50646. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50647. this.useCloseExponentialShadowMap = true;
  50648. return;
  50649. }
  50650. }
  50651. if (this._filter === value) {
  50652. return;
  50653. }
  50654. this._filter = value;
  50655. this._disposeBlurPostProcesses();
  50656. this._applyFilterValues();
  50657. this._light._markMeshesAsLightDirty();
  50658. },
  50659. enumerable: true,
  50660. configurable: true
  50661. });
  50662. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  50663. get: function () {
  50664. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  50665. },
  50666. set: function (value) {
  50667. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  50668. return;
  50669. }
  50670. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  50671. },
  50672. enumerable: true,
  50673. configurable: true
  50674. });
  50675. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  50676. get: function () {
  50677. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50678. return this.useExponentialShadowMap;
  50679. },
  50680. set: function (value) {
  50681. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50682. this.useExponentialShadowMap = value;
  50683. },
  50684. enumerable: true,
  50685. configurable: true
  50686. });
  50687. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  50688. get: function () {
  50689. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50690. return this.useBlurExponentialShadowMap;
  50691. },
  50692. set: function (value) {
  50693. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50694. this.useBlurExponentialShadowMap = value;
  50695. },
  50696. enumerable: true,
  50697. configurable: true
  50698. });
  50699. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  50700. get: function () {
  50701. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  50702. },
  50703. set: function (value) {
  50704. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  50705. return;
  50706. }
  50707. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50708. },
  50709. enumerable: true,
  50710. configurable: true
  50711. });
  50712. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  50713. get: function () {
  50714. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  50715. },
  50716. set: function (value) {
  50717. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50718. return;
  50719. }
  50720. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50721. },
  50722. enumerable: true,
  50723. configurable: true
  50724. });
  50725. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  50726. get: function () {
  50727. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50728. },
  50729. set: function (value) {
  50730. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  50731. return;
  50732. }
  50733. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50734. },
  50735. enumerable: true,
  50736. configurable: true
  50737. });
  50738. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  50739. get: function () {
  50740. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50741. },
  50742. set: function (value) {
  50743. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50744. return;
  50745. }
  50746. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50747. },
  50748. enumerable: true,
  50749. configurable: true
  50750. });
  50751. /**
  50752. * Returns the darkness value (float).
  50753. */
  50754. ShadowGenerator.prototype.getDarkness = function () {
  50755. return this._darkness;
  50756. };
  50757. /**
  50758. * Sets the ShadowGenerator darkness value (float <= 1.0).
  50759. * Returns the ShadowGenerator.
  50760. */
  50761. ShadowGenerator.prototype.setDarkness = function (darkness) {
  50762. if (darkness >= 1.0)
  50763. this._darkness = 1.0;
  50764. else if (darkness <= 0.0)
  50765. this._darkness = 0.0;
  50766. else
  50767. this._darkness = darkness;
  50768. return this;
  50769. };
  50770. /**
  50771. * Sets the ability to have transparent shadow (boolean).
  50772. * Returns the ShadowGenerator.
  50773. */
  50774. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  50775. this._transparencyShadow = hasShadow;
  50776. return this;
  50777. };
  50778. /**
  50779. * Returns a RenderTargetTexture object : the shadow map texture.
  50780. */
  50781. ShadowGenerator.prototype.getShadowMap = function () {
  50782. return this._shadowMap;
  50783. };
  50784. /**
  50785. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  50786. */
  50787. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  50788. if (this._shadowMap2) {
  50789. return this._shadowMap2;
  50790. }
  50791. return this._shadowMap;
  50792. };
  50793. /**
  50794. * Helper function to add a mesh and its descendants to the list of shadow casters
  50795. * @param mesh Mesh to add
  50796. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  50797. */
  50798. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  50799. if (includeDescendants === void 0) { includeDescendants = true; }
  50800. if (!this._shadowMap) {
  50801. return this;
  50802. }
  50803. if (!this._shadowMap.renderList) {
  50804. this._shadowMap.renderList = [];
  50805. }
  50806. this._shadowMap.renderList.push(mesh);
  50807. if (includeDescendants) {
  50808. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  50809. }
  50810. return this;
  50811. var _a;
  50812. };
  50813. /**
  50814. * Helper function to remove a mesh and its descendants from the list of shadow casters
  50815. * @param mesh Mesh to remove
  50816. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  50817. */
  50818. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  50819. if (includeDescendants === void 0) { includeDescendants = true; }
  50820. if (!this._shadowMap || !this._shadowMap.renderList) {
  50821. return this;
  50822. }
  50823. var index = this._shadowMap.renderList.indexOf(mesh);
  50824. if (index !== -1) {
  50825. this._shadowMap.renderList.splice(index, 1);
  50826. }
  50827. if (includeDescendants) {
  50828. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  50829. var child = _a[_i];
  50830. this.removeShadowCaster(child);
  50831. }
  50832. }
  50833. return this;
  50834. };
  50835. /**
  50836. * Returns the associated light object.
  50837. */
  50838. ShadowGenerator.prototype.getLight = function () {
  50839. return this._light;
  50840. };
  50841. ShadowGenerator.prototype._initializeGenerator = function () {
  50842. this._light._markMeshesAsLightDirty();
  50843. this._initializeShadowMap();
  50844. };
  50845. ShadowGenerator.prototype._initializeShadowMap = function () {
  50846. var _this = this;
  50847. // Render target
  50848. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  50849. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50850. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50851. this._shadowMap.anisotropicFilteringLevel = 1;
  50852. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50853. this._shadowMap.renderParticles = false;
  50854. this._shadowMap.ignoreCameraViewport = true;
  50855. // Record Face Index before render.
  50856. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  50857. _this._currentFaceIndex = faceIndex;
  50858. });
  50859. // Custom render function.
  50860. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  50861. // Blur if required afer render.
  50862. this._shadowMap.onAfterUnbindObservable.add(function () {
  50863. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  50864. return;
  50865. }
  50866. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  50867. _this._initializeBlurRTTAndPostProcesses();
  50868. }
  50869. var shadowMap = _this.getShadowMapForRendering();
  50870. if (shadowMap) {
  50871. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  50872. }
  50873. });
  50874. // Clear according to the chosen filter.
  50875. this._shadowMap.onClearObservable.add(function (engine) {
  50876. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  50877. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  50878. }
  50879. else {
  50880. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  50881. }
  50882. });
  50883. };
  50884. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  50885. var _this = this;
  50886. var engine = this._scene.getEngine();
  50887. var targetSize = this._mapSize / this.blurScale;
  50888. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  50889. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  50890. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50891. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50892. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50893. }
  50894. if (this.useKernelBlur) {
  50895. 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);
  50896. this._kernelBlurXPostprocess.width = targetSize;
  50897. this._kernelBlurXPostprocess.height = targetSize;
  50898. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  50899. effect.setTexture("textureSampler", _this._shadowMap);
  50900. });
  50901. 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);
  50902. this._kernelBlurXPostprocess.autoClear = false;
  50903. this._kernelBlurYPostprocess.autoClear = false;
  50904. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  50905. this._kernelBlurXPostprocess.packedFloat = true;
  50906. this._kernelBlurYPostprocess.packedFloat = true;
  50907. }
  50908. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  50909. }
  50910. else {
  50911. 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);
  50912. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  50913. effect.setFloat2("screenSize", targetSize, targetSize);
  50914. effect.setTexture("textureSampler", _this._shadowMap);
  50915. });
  50916. this._boxBlurPostprocess.autoClear = false;
  50917. this._blurPostProcesses = [this._boxBlurPostprocess];
  50918. }
  50919. };
  50920. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  50921. var index;
  50922. var engine = this._scene.getEngine();
  50923. if (depthOnlySubMeshes.length) {
  50924. engine.setColorWrite(false);
  50925. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  50926. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  50927. }
  50928. engine.setColorWrite(true);
  50929. }
  50930. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50931. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  50932. }
  50933. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50934. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  50935. }
  50936. if (this._transparencyShadow) {
  50937. for (index = 0; index < transparentSubMeshes.length; index++) {
  50938. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  50939. }
  50940. }
  50941. };
  50942. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  50943. var _this = this;
  50944. var mesh = subMesh.getRenderingMesh();
  50945. var scene = this._scene;
  50946. var engine = scene.getEngine();
  50947. var material = subMesh.getMaterial();
  50948. if (!material) {
  50949. return;
  50950. }
  50951. // Culling
  50952. engine.setState(material.backFaceCulling);
  50953. // Managing instances
  50954. var batch = mesh._getInstancesRenderList(subMesh._id);
  50955. if (batch.mustReturn) {
  50956. return;
  50957. }
  50958. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  50959. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  50960. engine.enableEffect(this._effect);
  50961. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  50962. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  50963. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  50964. this._effect.setVector3("lightPosition", this.getLight().position);
  50965. if (scene.activeCamera) {
  50966. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  50967. }
  50968. // Alpha test
  50969. if (material && material.needAlphaTesting()) {
  50970. var alphaTexture = material.getAlphaTestTexture();
  50971. if (alphaTexture) {
  50972. this._effect.setTexture("diffuseSampler", alphaTexture);
  50973. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  50974. }
  50975. }
  50976. // Bones
  50977. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50978. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  50979. }
  50980. if (this.forceBackFacesOnly) {
  50981. engine.setState(true, 0, false, true);
  50982. }
  50983. // Draw
  50984. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50985. if (this.forceBackFacesOnly) {
  50986. engine.setState(true, 0, false, false);
  50987. }
  50988. }
  50989. else {
  50990. // Need to reset refresh rate of the shadowMap
  50991. if (this._shadowMap) {
  50992. this._shadowMap.resetRefreshCounter();
  50993. }
  50994. }
  50995. };
  50996. ShadowGenerator.prototype._applyFilterValues = function () {
  50997. if (!this._shadowMap) {
  50998. return;
  50999. }
  51000. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51001. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51002. }
  51003. else {
  51004. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51005. }
  51006. };
  51007. /**
  51008. * Force shader compilation including textures ready check
  51009. */
  51010. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51011. var _this = this;
  51012. var shadowMap = this.getShadowMap();
  51013. if (!shadowMap) {
  51014. return;
  51015. }
  51016. var subMeshes = new Array();
  51017. var currentIndex = 0;
  51018. var renderList = shadowMap.renderList;
  51019. if (!renderList) {
  51020. return;
  51021. }
  51022. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51023. var mesh = renderList_1[_i];
  51024. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51025. }
  51026. var checkReady = function () {
  51027. if (!_this._scene || !_this._scene.getEngine()) {
  51028. return;
  51029. }
  51030. var subMesh = subMeshes[currentIndex];
  51031. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  51032. currentIndex++;
  51033. if (currentIndex >= subMeshes.length) {
  51034. if (onCompiled) {
  51035. onCompiled(_this);
  51036. }
  51037. return;
  51038. }
  51039. }
  51040. setTimeout(checkReady, 16);
  51041. };
  51042. if (subMeshes.length > 0) {
  51043. checkReady();
  51044. }
  51045. };
  51046. /**
  51047. * Boolean : true when the ShadowGenerator is finally computed.
  51048. */
  51049. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51050. var defines = [];
  51051. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51052. defines.push("#define FLOAT");
  51053. }
  51054. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51055. defines.push("#define ESM");
  51056. }
  51057. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51058. var mesh = subMesh.getMesh();
  51059. var material = subMesh.getMaterial();
  51060. // Alpha test
  51061. if (material && material.needAlphaTesting()) {
  51062. var alphaTexture = material.getAlphaTestTexture();
  51063. if (alphaTexture) {
  51064. defines.push("#define ALPHATEST");
  51065. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51066. attribs.push(BABYLON.VertexBuffer.UVKind);
  51067. defines.push("#define UV1");
  51068. }
  51069. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51070. if (alphaTexture.coordinatesIndex === 1) {
  51071. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51072. defines.push("#define UV2");
  51073. }
  51074. }
  51075. }
  51076. }
  51077. // Bones
  51078. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51079. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51080. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51081. if (mesh.numBoneInfluencers > 4) {
  51082. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51083. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51084. }
  51085. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51086. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51087. }
  51088. else {
  51089. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51090. }
  51091. // Instances
  51092. if (useInstances) {
  51093. defines.push("#define INSTANCES");
  51094. attribs.push("world0");
  51095. attribs.push("world1");
  51096. attribs.push("world2");
  51097. attribs.push("world3");
  51098. }
  51099. // Get correct effect
  51100. var join = defines.join("\n");
  51101. if (this._cachedDefines !== join) {
  51102. this._cachedDefines = join;
  51103. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51104. }
  51105. return this._effect.isReady();
  51106. };
  51107. /**
  51108. * This creates the defines related to the standard BJS materials.
  51109. */
  51110. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51111. var scene = this._scene;
  51112. var light = this._light;
  51113. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51114. return;
  51115. }
  51116. defines["SHADOW" + lightIndex] = true;
  51117. if (this.usePoissonSampling) {
  51118. defines["SHADOWPCF" + lightIndex] = true;
  51119. }
  51120. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51121. defines["SHADOWESM" + lightIndex] = true;
  51122. }
  51123. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51124. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51125. }
  51126. if (light.needCube()) {
  51127. defines["SHADOWCUBE" + lightIndex] = true;
  51128. }
  51129. };
  51130. /**
  51131. * This binds shadow lights related to the standard BJS materials.
  51132. * It implies the unifroms available on the materials are the standard BJS ones.
  51133. */
  51134. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51135. var light = this._light;
  51136. var scene = this._scene;
  51137. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51138. return;
  51139. }
  51140. var camera = scene.activeCamera;
  51141. if (!camera) {
  51142. return;
  51143. }
  51144. var shadowMap = this.getShadowMap();
  51145. if (!shadowMap) {
  51146. return;
  51147. }
  51148. if (!light.needCube()) {
  51149. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51150. }
  51151. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51152. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51153. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51154. };
  51155. // Methods
  51156. /**
  51157. * Returns a Matrix object : the updated transformation matrix.
  51158. */
  51159. ShadowGenerator.prototype.getTransformMatrix = function () {
  51160. var scene = this._scene;
  51161. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51162. return this._transformMatrix;
  51163. }
  51164. this._currentRenderID = scene.getRenderId();
  51165. this._currentFaceIndexCache = this._currentFaceIndex;
  51166. var lightPosition = this._light.position;
  51167. if (this._light.computeTransformedInformation()) {
  51168. lightPosition = this._light.transformedPosition;
  51169. }
  51170. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51171. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51172. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51173. }
  51174. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51175. this._cachedPosition = lightPosition.clone();
  51176. this._cachedDirection = this._lightDirection.clone();
  51177. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51178. var shadowMap = this.getShadowMap();
  51179. if (shadowMap) {
  51180. var renderList = shadowMap.renderList;
  51181. if (renderList) {
  51182. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51183. }
  51184. }
  51185. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51186. }
  51187. return this._transformMatrix;
  51188. };
  51189. ShadowGenerator.prototype.recreateShadowMap = function () {
  51190. var shadowMap = this._shadowMap;
  51191. if (!shadowMap) {
  51192. return;
  51193. }
  51194. // Track render list.
  51195. var renderList = shadowMap.renderList;
  51196. // Clean up existing data.
  51197. this._disposeRTTandPostProcesses();
  51198. // Reinitializes.
  51199. this._initializeGenerator();
  51200. // Reaffect the filter to ensure a correct fallback if necessary.
  51201. this.filter = this.filter;
  51202. // Reaffect the filter.
  51203. this._applyFilterValues();
  51204. // Reaffect Render List.
  51205. shadowMap.renderList = renderList;
  51206. };
  51207. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51208. if (this._shadowMap2) {
  51209. this._shadowMap2.dispose();
  51210. this._shadowMap2 = null;
  51211. }
  51212. if (this._downSamplePostprocess) {
  51213. this._downSamplePostprocess.dispose();
  51214. this._downSamplePostprocess = null;
  51215. }
  51216. if (this._boxBlurPostprocess) {
  51217. this._boxBlurPostprocess.dispose();
  51218. this._boxBlurPostprocess = null;
  51219. }
  51220. if (this._kernelBlurXPostprocess) {
  51221. this._kernelBlurXPostprocess.dispose();
  51222. this._kernelBlurXPostprocess = null;
  51223. }
  51224. if (this._kernelBlurYPostprocess) {
  51225. this._kernelBlurYPostprocess.dispose();
  51226. this._kernelBlurYPostprocess = null;
  51227. }
  51228. this._blurPostProcesses = [];
  51229. };
  51230. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51231. if (this._shadowMap) {
  51232. this._shadowMap.dispose();
  51233. this._shadowMap = null;
  51234. }
  51235. this._disposeBlurPostProcesses();
  51236. };
  51237. /**
  51238. * Disposes the ShadowGenerator.
  51239. * Returns nothing.
  51240. */
  51241. ShadowGenerator.prototype.dispose = function () {
  51242. this._disposeRTTandPostProcesses();
  51243. if (this._light) {
  51244. this._light._shadowGenerator = null;
  51245. this._light._markMeshesAsLightDirty();
  51246. }
  51247. };
  51248. /**
  51249. * Serializes the ShadowGenerator and returns a serializationObject.
  51250. */
  51251. ShadowGenerator.prototype.serialize = function () {
  51252. var serializationObject = {};
  51253. var shadowMap = this.getShadowMap();
  51254. if (!shadowMap) {
  51255. return serializationObject;
  51256. }
  51257. serializationObject.lightId = this._light.id;
  51258. serializationObject.mapSize = shadowMap.getRenderSize();
  51259. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51260. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51261. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51262. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51263. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51264. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51265. serializationObject.depthScale = this.depthScale;
  51266. serializationObject.darkness = this.getDarkness();
  51267. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51268. serializationObject.blurKernel = this.blurKernel;
  51269. serializationObject.blurScale = this.blurScale;
  51270. serializationObject.useKernelBlur = this.useKernelBlur;
  51271. serializationObject.transparencyShadow = this._transparencyShadow;
  51272. serializationObject.renderList = [];
  51273. if (shadowMap.renderList) {
  51274. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51275. var mesh = shadowMap.renderList[meshIndex];
  51276. serializationObject.renderList.push(mesh.id);
  51277. }
  51278. }
  51279. return serializationObject;
  51280. };
  51281. /**
  51282. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51283. */
  51284. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51285. //casting to point light, as light is missing the position attr and typescript complains.
  51286. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51287. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51288. var shadowMap = shadowGenerator.getShadowMap();
  51289. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51290. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51291. meshes.forEach(function (mesh) {
  51292. if (!shadowMap) {
  51293. return;
  51294. }
  51295. if (!shadowMap.renderList) {
  51296. shadowMap.renderList = [];
  51297. }
  51298. shadowMap.renderList.push(mesh);
  51299. });
  51300. }
  51301. if (parsedShadowGenerator.usePoissonSampling) {
  51302. shadowGenerator.usePoissonSampling = true;
  51303. }
  51304. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51305. shadowGenerator.useExponentialShadowMap = true;
  51306. }
  51307. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51308. shadowGenerator.useBlurExponentialShadowMap = true;
  51309. }
  51310. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51311. shadowGenerator.useCloseExponentialShadowMap = true;
  51312. }
  51313. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51314. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51315. }
  51316. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51317. shadowGenerator.useExponentialShadowMap = true;
  51318. }
  51319. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51320. shadowGenerator.useBlurExponentialShadowMap = true;
  51321. }
  51322. if (parsedShadowGenerator.depthScale) {
  51323. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51324. }
  51325. if (parsedShadowGenerator.blurScale) {
  51326. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51327. }
  51328. if (parsedShadowGenerator.blurBoxOffset) {
  51329. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51330. }
  51331. if (parsedShadowGenerator.useKernelBlur) {
  51332. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51333. }
  51334. if (parsedShadowGenerator.blurKernel) {
  51335. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51336. }
  51337. if (parsedShadowGenerator.bias !== undefined) {
  51338. shadowGenerator.bias = parsedShadowGenerator.bias;
  51339. }
  51340. if (parsedShadowGenerator.darkness) {
  51341. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51342. }
  51343. if (parsedShadowGenerator.transparencyShadow) {
  51344. shadowGenerator.setTransparencyShadow(true);
  51345. }
  51346. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51347. return shadowGenerator;
  51348. };
  51349. ShadowGenerator._FILTER_NONE = 0;
  51350. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51351. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51352. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51353. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51354. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51355. return ShadowGenerator;
  51356. }());
  51357. BABYLON.ShadowGenerator = ShadowGenerator;
  51358. })(BABYLON || (BABYLON = {}));
  51359. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51360. var BABYLON;
  51361. (function (BABYLON) {
  51362. var DefaultLoadingScreen = /** @class */ (function () {
  51363. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51364. if (_loadingText === void 0) { _loadingText = ""; }
  51365. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51366. var _this = this;
  51367. this._renderingCanvas = _renderingCanvas;
  51368. this._loadingText = _loadingText;
  51369. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51370. // Resize
  51371. this._resizeLoadingUI = function () {
  51372. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51373. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51374. if (!_this._loadingDiv) {
  51375. return;
  51376. }
  51377. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51378. _this._loadingDiv.style.left = canvasRect.left + "px";
  51379. _this._loadingDiv.style.top = canvasRect.top + "px";
  51380. _this._loadingDiv.style.width = canvasRect.width + "px";
  51381. _this._loadingDiv.style.height = canvasRect.height + "px";
  51382. };
  51383. }
  51384. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51385. if (this._loadingDiv) {
  51386. // Do not add a loading screen if there is already one
  51387. return;
  51388. }
  51389. this._loadingDiv = document.createElement("div");
  51390. this._loadingDiv.id = "babylonjsLoadingDiv";
  51391. this._loadingDiv.style.opacity = "0";
  51392. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51393. this._loadingDiv.style.pointerEvents = "none";
  51394. // Loading text
  51395. this._loadingTextDiv = document.createElement("div");
  51396. this._loadingTextDiv.style.position = "absolute";
  51397. this._loadingTextDiv.style.left = "0";
  51398. this._loadingTextDiv.style.top = "50%";
  51399. this._loadingTextDiv.style.marginTop = "80px";
  51400. this._loadingTextDiv.style.width = "100%";
  51401. this._loadingTextDiv.style.height = "20px";
  51402. this._loadingTextDiv.style.fontFamily = "Arial";
  51403. this._loadingTextDiv.style.fontSize = "14px";
  51404. this._loadingTextDiv.style.color = "white";
  51405. this._loadingTextDiv.style.textAlign = "center";
  51406. this._loadingTextDiv.innerHTML = "Loading";
  51407. this._loadingDiv.appendChild(this._loadingTextDiv);
  51408. //set the predefined text
  51409. this._loadingTextDiv.innerHTML = this._loadingText;
  51410. // Generating keyframes
  51411. var style = document.createElement('style');
  51412. style.type = 'text/css';
  51413. 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 }";
  51414. style.innerHTML = keyFrames;
  51415. document.getElementsByTagName('head')[0].appendChild(style);
  51416. // Loading img
  51417. var imgBack = new Image();
  51418. 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";
  51419. imgBack.style.position = "absolute";
  51420. imgBack.style.left = "50%";
  51421. imgBack.style.top = "50%";
  51422. imgBack.style.marginLeft = "-60px";
  51423. imgBack.style.marginTop = "-60px";
  51424. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51425. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51426. imgBack.style.transformOrigin = "50% 50%";
  51427. imgBack.style.webkitTransformOrigin = "50% 50%";
  51428. this._loadingDiv.appendChild(imgBack);
  51429. this._resizeLoadingUI();
  51430. window.addEventListener("resize", this._resizeLoadingUI);
  51431. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51432. document.body.appendChild(this._loadingDiv);
  51433. this._loadingDiv.style.opacity = "1";
  51434. };
  51435. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51436. var _this = this;
  51437. if (!this._loadingDiv) {
  51438. return;
  51439. }
  51440. var onTransitionEnd = function () {
  51441. if (!_this._loadingDiv) {
  51442. return;
  51443. }
  51444. document.body.removeChild(_this._loadingDiv);
  51445. window.removeEventListener("resize", _this._resizeLoadingUI);
  51446. _this._loadingDiv = null;
  51447. };
  51448. this._loadingDiv.style.opacity = "0";
  51449. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51450. };
  51451. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51452. set: function (text) {
  51453. this._loadingText = text;
  51454. if (this._loadingTextDiv) {
  51455. this._loadingTextDiv.innerHTML = this._loadingText;
  51456. }
  51457. },
  51458. enumerable: true,
  51459. configurable: true
  51460. });
  51461. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51462. get: function () {
  51463. return this._loadingDivBackgroundColor;
  51464. },
  51465. set: function (color) {
  51466. this._loadingDivBackgroundColor = color;
  51467. if (!this._loadingDiv) {
  51468. return;
  51469. }
  51470. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51471. },
  51472. enumerable: true,
  51473. configurable: true
  51474. });
  51475. return DefaultLoadingScreen;
  51476. }());
  51477. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51478. })(BABYLON || (BABYLON = {}));
  51479. //# sourceMappingURL=babylon.loadingScreen.js.map
  51480. var BABYLON;
  51481. (function (BABYLON) {
  51482. var SceneLoader = /** @class */ (function () {
  51483. function SceneLoader() {
  51484. }
  51485. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51486. get: function () {
  51487. return 0;
  51488. },
  51489. enumerable: true,
  51490. configurable: true
  51491. });
  51492. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51493. get: function () {
  51494. return 1;
  51495. },
  51496. enumerable: true,
  51497. configurable: true
  51498. });
  51499. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51500. get: function () {
  51501. return 2;
  51502. },
  51503. enumerable: true,
  51504. configurable: true
  51505. });
  51506. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51507. get: function () {
  51508. return 3;
  51509. },
  51510. enumerable: true,
  51511. configurable: true
  51512. });
  51513. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51514. get: function () {
  51515. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51516. },
  51517. set: function (value) {
  51518. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51519. },
  51520. enumerable: true,
  51521. configurable: true
  51522. });
  51523. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51524. get: function () {
  51525. return SceneLoader._ShowLoadingScreen;
  51526. },
  51527. set: function (value) {
  51528. SceneLoader._ShowLoadingScreen = value;
  51529. },
  51530. enumerable: true,
  51531. configurable: true
  51532. });
  51533. Object.defineProperty(SceneLoader, "loggingLevel", {
  51534. get: function () {
  51535. return SceneLoader._loggingLevel;
  51536. },
  51537. set: function (value) {
  51538. SceneLoader._loggingLevel = value;
  51539. },
  51540. enumerable: true,
  51541. configurable: true
  51542. });
  51543. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51544. get: function () {
  51545. return SceneLoader._CleanBoneMatrixWeights;
  51546. },
  51547. set: function (value) {
  51548. SceneLoader._CleanBoneMatrixWeights = value;
  51549. },
  51550. enumerable: true,
  51551. configurable: true
  51552. });
  51553. SceneLoader._getDefaultPlugin = function () {
  51554. return SceneLoader._registeredPlugins[".babylon"];
  51555. };
  51556. SceneLoader._getPluginForExtension = function (extension) {
  51557. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  51558. if (registeredPlugin) {
  51559. return registeredPlugin;
  51560. }
  51561. return SceneLoader._getDefaultPlugin();
  51562. };
  51563. SceneLoader._getPluginForDirectLoad = function (data) {
  51564. for (var extension in SceneLoader._registeredPlugins) {
  51565. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  51566. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  51567. return SceneLoader._registeredPlugins[extension];
  51568. }
  51569. }
  51570. return SceneLoader._getDefaultPlugin();
  51571. };
  51572. SceneLoader._getPluginForFilename = function (sceneFilename) {
  51573. if (sceneFilename.name) {
  51574. sceneFilename = sceneFilename.name;
  51575. }
  51576. var dotPosition = sceneFilename.lastIndexOf(".");
  51577. var queryStringPosition = sceneFilename.indexOf("?");
  51578. if (queryStringPosition === -1) {
  51579. queryStringPosition = sceneFilename.length;
  51580. }
  51581. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  51582. return SceneLoader._getPluginForExtension(extension);
  51583. };
  51584. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  51585. SceneLoader._getDirectLoad = function (sceneFilename) {
  51586. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  51587. return sceneFilename.substr(5);
  51588. }
  51589. return null;
  51590. };
  51591. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51592. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  51593. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  51594. var plugin = registeredPlugin.plugin;
  51595. var useArrayBuffer = registeredPlugin.isBinary;
  51596. var database;
  51597. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  51598. var dataCallback = function (data) {
  51599. if (scene.isDisposed) {
  51600. onError("Scene has been disposed");
  51601. return;
  51602. }
  51603. scene.database = database;
  51604. try {
  51605. onSuccess(plugin, data);
  51606. }
  51607. catch (e) {
  51608. onError(null, e);
  51609. }
  51610. };
  51611. var manifestChecked = function (success) {
  51612. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  51613. if (request) {
  51614. onError(request.status + " " + request.statusText);
  51615. }
  51616. });
  51617. };
  51618. if (directLoad) {
  51619. dataCallback(directLoad);
  51620. return;
  51621. }
  51622. if (rootUrl.indexOf("file:") === -1) {
  51623. if (scene.getEngine().enableOfflineSupport) {
  51624. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  51625. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  51626. }
  51627. else {
  51628. manifestChecked(true);
  51629. }
  51630. }
  51631. else {
  51632. var fileOrString = sceneFilename;
  51633. if (fileOrString.name) {
  51634. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  51635. }
  51636. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  51637. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  51638. }
  51639. else {
  51640. onError("Unable to find file named " + sceneFilename);
  51641. return;
  51642. }
  51643. }
  51644. };
  51645. // Public functions
  51646. SceneLoader.GetPluginForExtension = function (extension) {
  51647. return SceneLoader._getPluginForExtension(extension).plugin;
  51648. };
  51649. SceneLoader.RegisterPlugin = function (plugin) {
  51650. if (typeof plugin.extensions === "string") {
  51651. var extension = plugin.extensions;
  51652. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51653. plugin: plugin,
  51654. isBinary: false
  51655. };
  51656. }
  51657. else {
  51658. var extensions = plugin.extensions;
  51659. Object.keys(extensions).forEach(function (extension) {
  51660. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51661. plugin: plugin,
  51662. isBinary: extensions[extension].isBinary
  51663. };
  51664. });
  51665. }
  51666. };
  51667. /**
  51668. * Import meshes into a scene
  51669. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  51670. * @param rootUrl a string that defines the root url for scene and resources
  51671. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51672. * @param scene the instance of BABYLON.Scene to append to
  51673. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  51674. * @param onProgress a callback with a progress event for each file being loaded
  51675. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51676. */
  51677. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51678. if (onSuccess === void 0) { onSuccess = null; }
  51679. if (onProgress === void 0) { onProgress = null; }
  51680. if (onError === void 0) { onError = null; }
  51681. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51682. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51683. return;
  51684. }
  51685. var loadingToken = {};
  51686. scene._addPendingData(loadingToken);
  51687. var errorHandler = function (message, exception) {
  51688. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51689. if (onError) {
  51690. onError(scene, errorMessage, exception);
  51691. }
  51692. else {
  51693. BABYLON.Tools.Error(errorMessage);
  51694. // should the exception be thrown?
  51695. }
  51696. scene._removePendingData(loadingToken);
  51697. };
  51698. var progressHandler = function (event) {
  51699. if (onProgress) {
  51700. onProgress(event);
  51701. }
  51702. };
  51703. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51704. if (plugin.importMesh) {
  51705. var syncedPlugin = plugin;
  51706. var meshes = new Array();
  51707. var particleSystems = new Array();
  51708. var skeletons = new Array();
  51709. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  51710. return;
  51711. }
  51712. if (onSuccess) {
  51713. // wrap onSuccess with try-catch to know if something went wrong.
  51714. try {
  51715. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51716. onSuccess(meshes, particleSystems, skeletons);
  51717. scene._removePendingData(loadingToken);
  51718. }
  51719. catch (e) {
  51720. var message = 'Error in onSuccess callback.';
  51721. errorHandler(message, e);
  51722. }
  51723. }
  51724. }
  51725. else {
  51726. var asyncedPlugin = plugin;
  51727. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  51728. if (onSuccess) {
  51729. try {
  51730. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51731. onSuccess(meshes, particleSystems, skeletons);
  51732. scene._removePendingData(loadingToken);
  51733. }
  51734. catch (e) {
  51735. var message = 'Error in onSuccess callback.';
  51736. errorHandler(message, e);
  51737. }
  51738. }
  51739. }, progressHandler, errorHandler);
  51740. }
  51741. }, progressHandler, errorHandler);
  51742. };
  51743. /**
  51744. * Load a scene
  51745. * @param rootUrl a string that defines the root url for scene and resources
  51746. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51747. * @param engine is the instance of BABYLON.Engine to use to create the scene
  51748. * @param onSuccess a callback with the scene when import succeeds
  51749. * @param onProgress a callback with a progress event for each file being loaded
  51750. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51751. */
  51752. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  51753. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  51754. };
  51755. /**
  51756. * Append a scene
  51757. * @param rootUrl a string that defines the root url for scene and resources
  51758. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51759. * @param scene is the instance of BABYLON.Scene to append to
  51760. * @param onSuccess a callback with the scene when import succeeds
  51761. * @param onProgress a callback with a progress event for each file being loaded
  51762. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51763. */
  51764. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51765. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51766. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51767. return;
  51768. }
  51769. if (SceneLoader.ShowLoadingScreen) {
  51770. scene.getEngine().displayLoadingUI();
  51771. }
  51772. var loadingToken = {};
  51773. scene._addPendingData(loadingToken);
  51774. var errorHandler = function (message, exception) {
  51775. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51776. if (onError) {
  51777. onError(scene, errorMessage, exception);
  51778. }
  51779. else {
  51780. BABYLON.Tools.Error(errorMessage);
  51781. // should the exception be thrown?
  51782. }
  51783. scene._removePendingData(loadingToken);
  51784. scene.getEngine().hideLoadingUI();
  51785. };
  51786. var progressHandler = function (event) {
  51787. if (onProgress) {
  51788. onProgress(event);
  51789. }
  51790. };
  51791. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51792. if (plugin.load) {
  51793. var syncedPlugin = plugin;
  51794. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  51795. return;
  51796. }
  51797. if (onSuccess) {
  51798. try {
  51799. onSuccess(scene);
  51800. }
  51801. catch (e) {
  51802. errorHandler("Error in onSuccess callback", e);
  51803. }
  51804. }
  51805. scene.loadingPluginName = plugin.name;
  51806. scene._removePendingData(loadingToken);
  51807. }
  51808. else {
  51809. var asyncedPlugin = plugin;
  51810. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  51811. if (onSuccess) {
  51812. onSuccess(scene);
  51813. }
  51814. scene.loadingPluginName = plugin.name;
  51815. scene._removePendingData(loadingToken);
  51816. }, progressHandler, errorHandler);
  51817. }
  51818. if (SceneLoader.ShowLoadingScreen) {
  51819. scene.executeWhenReady(function () {
  51820. scene.getEngine().hideLoadingUI();
  51821. });
  51822. }
  51823. }, progressHandler, errorHandler);
  51824. };
  51825. // Flags
  51826. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  51827. SceneLoader._ShowLoadingScreen = true;
  51828. SceneLoader._CleanBoneMatrixWeights = false;
  51829. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  51830. // Members
  51831. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  51832. SceneLoader._registeredPlugins = {};
  51833. return SceneLoader;
  51834. }());
  51835. BABYLON.SceneLoader = SceneLoader;
  51836. ;
  51837. })(BABYLON || (BABYLON = {}));
  51838. //# sourceMappingURL=babylon.sceneLoader.js.map
  51839. var BABYLON;
  51840. (function (BABYLON) {
  51841. var Internals;
  51842. (function (Internals) {
  51843. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  51844. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  51845. var parsedMaterial = parsedData.materials[index];
  51846. if (parsedMaterial.id === id) {
  51847. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  51848. }
  51849. }
  51850. return null;
  51851. };
  51852. var isDescendantOf = function (mesh, names, hierarchyIds) {
  51853. for (var i in names) {
  51854. if (mesh.name === names[i]) {
  51855. hierarchyIds.push(mesh.id);
  51856. return true;
  51857. }
  51858. }
  51859. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  51860. hierarchyIds.push(mesh.id);
  51861. return true;
  51862. }
  51863. return false;
  51864. };
  51865. var logOperation = function (operation, producer) {
  51866. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  51867. };
  51868. BABYLON.SceneLoader.RegisterPlugin({
  51869. name: "babylon.js",
  51870. extensions: ".babylon",
  51871. canDirectLoad: function (data) {
  51872. if (data.indexOf("babylon") !== -1) {
  51873. return true;
  51874. }
  51875. return false;
  51876. },
  51877. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  51878. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  51879. // when SceneLoader.debugLogging = true (default), or exception encountered.
  51880. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  51881. // and avoid problems with multiple concurrent .babylon loads.
  51882. var log = "importMesh has failed JSON parse";
  51883. try {
  51884. var parsedData = JSON.parse(data);
  51885. log = "";
  51886. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  51887. if (!meshesNames) {
  51888. meshesNames = null;
  51889. }
  51890. else if (!Array.isArray(meshesNames)) {
  51891. meshesNames = [meshesNames];
  51892. }
  51893. var hierarchyIds = new Array();
  51894. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  51895. var loadedSkeletonsIds = [];
  51896. var loadedMaterialsIds = [];
  51897. var index;
  51898. var cache;
  51899. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  51900. var parsedMesh = parsedData.meshes[index];
  51901. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  51902. if (meshesNames !== null) {
  51903. // Remove found mesh name from list.
  51904. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  51905. }
  51906. //Geometry?
  51907. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  51908. //does the file contain geometries?
  51909. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  51910. //find the correct geometry and add it to the scene
  51911. var found = false;
  51912. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  51913. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  51914. return;
  51915. }
  51916. else {
  51917. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  51918. if (parsedGeometryData.id === parsedMesh.geometryId) {
  51919. switch (geometryType) {
  51920. case "boxes":
  51921. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  51922. break;
  51923. case "spheres":
  51924. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  51925. break;
  51926. case "cylinders":
  51927. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  51928. break;
  51929. case "toruses":
  51930. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  51931. break;
  51932. case "grounds":
  51933. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  51934. break;
  51935. case "planes":
  51936. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  51937. break;
  51938. case "torusKnots":
  51939. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  51940. break;
  51941. case "vertexData":
  51942. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  51943. break;
  51944. }
  51945. found = true;
  51946. }
  51947. });
  51948. }
  51949. });
  51950. if (found === false) {
  51951. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  51952. }
  51953. }
  51954. }
  51955. // Material ?
  51956. if (parsedMesh.materialId) {
  51957. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  51958. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  51959. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  51960. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  51961. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  51962. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  51963. var subMatId = parsedMultiMaterial.materials[matIndex];
  51964. loadedMaterialsIds.push(subMatId);
  51965. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  51966. log += "\n\tMaterial " + mat.toString(fullDetails);
  51967. }
  51968. loadedMaterialsIds.push(parsedMultiMaterial.id);
  51969. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  51970. materialFound = true;
  51971. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  51972. break;
  51973. }
  51974. }
  51975. }
  51976. if (materialFound === false) {
  51977. loadedMaterialsIds.push(parsedMesh.materialId);
  51978. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  51979. if (!mat) {
  51980. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  51981. }
  51982. else {
  51983. log += "\n\tMaterial " + mat.toString(fullDetails);
  51984. }
  51985. }
  51986. }
  51987. // Skeleton ?
  51988. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  51989. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  51990. if (skeletonAlreadyLoaded === false) {
  51991. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  51992. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  51993. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  51994. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  51995. skeletons.push(skeleton);
  51996. loadedSkeletonsIds.push(parsedSkeleton.id);
  51997. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  51998. }
  51999. }
  52000. }
  52001. }
  52002. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52003. meshes.push(mesh);
  52004. log += "\n\tMesh " + mesh.toString(fullDetails);
  52005. }
  52006. }
  52007. // Connecting parents
  52008. var currentMesh;
  52009. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52010. currentMesh = scene.meshes[index];
  52011. if (currentMesh._waitingParentId) {
  52012. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52013. currentMesh._waitingParentId = null;
  52014. }
  52015. }
  52016. // freeze and compute world matrix application
  52017. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52018. currentMesh = scene.meshes[index];
  52019. if (currentMesh._waitingFreezeWorldMatrix) {
  52020. currentMesh.freezeWorldMatrix();
  52021. currentMesh._waitingFreezeWorldMatrix = null;
  52022. }
  52023. else {
  52024. currentMesh.computeWorldMatrix(true);
  52025. }
  52026. }
  52027. }
  52028. // Particles
  52029. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52030. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52031. var parsedParticleSystem = parsedData.particleSystems[index];
  52032. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52033. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52034. }
  52035. }
  52036. }
  52037. return true;
  52038. }
  52039. catch (err) {
  52040. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52041. if (onError) {
  52042. onError(msg, err);
  52043. }
  52044. else {
  52045. BABYLON.Tools.Log(msg);
  52046. throw err;
  52047. }
  52048. }
  52049. finally {
  52050. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52051. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52052. }
  52053. }
  52054. return false;
  52055. },
  52056. load: function (scene, data, rootUrl, onError) {
  52057. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52058. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52059. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52060. // and avoid problems with multiple concurrent .babylon loads.
  52061. var log = "importScene has failed JSON parse";
  52062. try {
  52063. var parsedData = JSON.parse(data);
  52064. log = "";
  52065. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52066. // Scene
  52067. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52068. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52069. }
  52070. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52071. scene.autoClear = parsedData.autoClear;
  52072. }
  52073. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52074. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52075. }
  52076. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52077. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52078. }
  52079. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52080. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52081. }
  52082. // Fog
  52083. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52084. scene.fogMode = parsedData.fogMode;
  52085. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52086. scene.fogStart = parsedData.fogStart;
  52087. scene.fogEnd = parsedData.fogEnd;
  52088. scene.fogDensity = parsedData.fogDensity;
  52089. log += "\tFog mode for scene: ";
  52090. switch (scene.fogMode) {
  52091. // getters not compiling, so using hardcoded
  52092. case 1:
  52093. log += "exp\n";
  52094. break;
  52095. case 2:
  52096. log += "exp2\n";
  52097. break;
  52098. case 3:
  52099. log += "linear\n";
  52100. break;
  52101. }
  52102. }
  52103. //Physics
  52104. if (parsedData.physicsEnabled) {
  52105. var physicsPlugin;
  52106. if (parsedData.physicsEngine === "cannon") {
  52107. physicsPlugin = new BABYLON.CannonJSPlugin();
  52108. }
  52109. else if (parsedData.physicsEngine === "oimo") {
  52110. physicsPlugin = new BABYLON.OimoJSPlugin();
  52111. }
  52112. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52113. //else - default engine, which is currently oimo
  52114. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52115. scene.enablePhysics(physicsGravity, physicsPlugin);
  52116. }
  52117. // Metadata
  52118. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52119. scene.metadata = parsedData.metadata;
  52120. }
  52121. //collisions, if defined. otherwise, default is true
  52122. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52123. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52124. }
  52125. scene.workerCollisions = !!parsedData.workerCollisions;
  52126. var index;
  52127. var cache;
  52128. // Lights
  52129. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52130. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52131. var parsedLight = parsedData.lights[index];
  52132. var light = BABYLON.Light.Parse(parsedLight, scene);
  52133. if (light) {
  52134. log += (index === 0 ? "\n\tLights:" : "");
  52135. log += "\n\t\t" + light.toString(fullDetails);
  52136. }
  52137. }
  52138. }
  52139. // Animations
  52140. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52141. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52142. var parsedAnimation = parsedData.animations[index];
  52143. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52144. scene.animations.push(animation);
  52145. log += (index === 0 ? "\n\tAnimations:" : "");
  52146. log += "\n\t\t" + animation.toString(fullDetails);
  52147. }
  52148. }
  52149. if (parsedData.autoAnimate) {
  52150. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52151. }
  52152. // Materials
  52153. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52154. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52155. var parsedMaterial = parsedData.materials[index];
  52156. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52157. log += (index === 0 ? "\n\tMaterials:" : "");
  52158. log += "\n\t\t" + mat.toString(fullDetails);
  52159. }
  52160. }
  52161. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52162. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52163. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52164. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52165. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52166. log += "\n\t\t" + mmat.toString(fullDetails);
  52167. }
  52168. }
  52169. // Morph targets
  52170. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52171. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52172. var managerData = _a[_i];
  52173. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52174. }
  52175. }
  52176. // Skeletons
  52177. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52178. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52179. var parsedSkeleton = parsedData.skeletons[index];
  52180. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52181. log += (index === 0 ? "\n\tSkeletons:" : "");
  52182. log += "\n\t\t" + skeleton.toString(fullDetails);
  52183. }
  52184. }
  52185. // Geometries
  52186. var geometries = parsedData.geometries;
  52187. if (geometries !== undefined && geometries !== null) {
  52188. // Boxes
  52189. var boxes = geometries.boxes;
  52190. if (boxes !== undefined && boxes !== null) {
  52191. for (index = 0, cache = boxes.length; index < cache; index++) {
  52192. var parsedBox = boxes[index];
  52193. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52194. }
  52195. }
  52196. // Spheres
  52197. var spheres = geometries.spheres;
  52198. if (spheres !== undefined && spheres !== null) {
  52199. for (index = 0, cache = spheres.length; index < cache; index++) {
  52200. var parsedSphere = spheres[index];
  52201. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52202. }
  52203. }
  52204. // Cylinders
  52205. var cylinders = geometries.cylinders;
  52206. if (cylinders !== undefined && cylinders !== null) {
  52207. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52208. var parsedCylinder = cylinders[index];
  52209. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52210. }
  52211. }
  52212. // Toruses
  52213. var toruses = geometries.toruses;
  52214. if (toruses !== undefined && toruses !== null) {
  52215. for (index = 0, cache = toruses.length; index < cache; index++) {
  52216. var parsedTorus = toruses[index];
  52217. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52218. }
  52219. }
  52220. // Grounds
  52221. var grounds = geometries.grounds;
  52222. if (grounds !== undefined && grounds !== null) {
  52223. for (index = 0, cache = grounds.length; index < cache; index++) {
  52224. var parsedGround = grounds[index];
  52225. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52226. }
  52227. }
  52228. // Planes
  52229. var planes = geometries.planes;
  52230. if (planes !== undefined && planes !== null) {
  52231. for (index = 0, cache = planes.length; index < cache; index++) {
  52232. var parsedPlane = planes[index];
  52233. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52234. }
  52235. }
  52236. // TorusKnots
  52237. var torusKnots = geometries.torusKnots;
  52238. if (torusKnots !== undefined && torusKnots !== null) {
  52239. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52240. var parsedTorusKnot = torusKnots[index];
  52241. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52242. }
  52243. }
  52244. // VertexData
  52245. var vertexData = geometries.vertexData;
  52246. if (vertexData !== undefined && vertexData !== null) {
  52247. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52248. var parsedVertexData = vertexData[index];
  52249. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52250. }
  52251. }
  52252. }
  52253. // Meshes
  52254. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52255. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52256. var parsedMesh = parsedData.meshes[index];
  52257. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52258. log += (index === 0 ? "\n\tMeshes:" : "");
  52259. log += "\n\t\t" + mesh.toString(fullDetails);
  52260. }
  52261. }
  52262. // Cameras
  52263. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52264. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52265. var parsedCamera = parsedData.cameras[index];
  52266. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52267. log += (index === 0 ? "\n\tCameras:" : "");
  52268. log += "\n\t\t" + camera.toString(fullDetails);
  52269. }
  52270. }
  52271. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52272. scene.setActiveCameraByID(parsedData.activeCameraID);
  52273. }
  52274. // Browsing all the graph to connect the dots
  52275. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52276. var camera = scene.cameras[index];
  52277. if (camera._waitingParentId) {
  52278. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52279. camera._waitingParentId = null;
  52280. }
  52281. }
  52282. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52283. var light_1 = scene.lights[index];
  52284. if (light_1 && light_1._waitingParentId) {
  52285. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52286. light_1._waitingParentId = null;
  52287. }
  52288. }
  52289. // Sounds
  52290. var loadedSounds = [];
  52291. var loadedSound;
  52292. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52293. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52294. var parsedSound = parsedData.sounds[index];
  52295. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52296. if (!parsedSound.url)
  52297. parsedSound.url = parsedSound.name;
  52298. if (!loadedSounds[parsedSound.url]) {
  52299. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52300. loadedSounds[parsedSound.url] = loadedSound;
  52301. }
  52302. else {
  52303. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52304. }
  52305. }
  52306. else {
  52307. new BABYLON.Sound(parsedSound.name, null, scene);
  52308. }
  52309. }
  52310. }
  52311. loadedSounds = [];
  52312. // Connect parents & children and parse actions
  52313. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52314. var mesh = scene.meshes[index];
  52315. if (mesh._waitingParentId) {
  52316. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52317. mesh._waitingParentId = null;
  52318. }
  52319. if (mesh._waitingActions) {
  52320. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52321. mesh._waitingActions = null;
  52322. }
  52323. }
  52324. // freeze world matrix application
  52325. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52326. var currentMesh = scene.meshes[index];
  52327. if (currentMesh._waitingFreezeWorldMatrix) {
  52328. currentMesh.freezeWorldMatrix();
  52329. currentMesh._waitingFreezeWorldMatrix = null;
  52330. }
  52331. else {
  52332. currentMesh.computeWorldMatrix(true);
  52333. }
  52334. }
  52335. // Particles Systems
  52336. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52337. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52338. var parsedParticleSystem = parsedData.particleSystems[index];
  52339. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52340. }
  52341. }
  52342. // Environment texture
  52343. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52344. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52345. if (parsedData.createDefaultSkybox === true) {
  52346. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52347. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52348. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52349. }
  52350. }
  52351. // Lens flares
  52352. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52353. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52354. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52355. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52356. }
  52357. }
  52358. // Shadows
  52359. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52360. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52361. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52362. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52363. }
  52364. }
  52365. // Lights exclusions / inclusions
  52366. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52367. var light_2 = scene.lights[index];
  52368. // Excluded check
  52369. if (light_2._excludedMeshesIds.length > 0) {
  52370. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52371. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52372. if (excludedMesh) {
  52373. light_2.excludedMeshes.push(excludedMesh);
  52374. }
  52375. }
  52376. light_2._excludedMeshesIds = [];
  52377. }
  52378. // Included check
  52379. if (light_2._includedOnlyMeshesIds.length > 0) {
  52380. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52381. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52382. if (includedOnlyMesh) {
  52383. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52384. }
  52385. }
  52386. light_2._includedOnlyMeshesIds = [];
  52387. }
  52388. }
  52389. // Actions (scene)
  52390. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52391. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52392. }
  52393. // Finish
  52394. return true;
  52395. }
  52396. catch (err) {
  52397. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52398. if (onError) {
  52399. onError(msg, err);
  52400. }
  52401. else {
  52402. BABYLON.Tools.Log(msg);
  52403. throw err;
  52404. }
  52405. }
  52406. finally {
  52407. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52408. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52409. }
  52410. }
  52411. return false;
  52412. }
  52413. });
  52414. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52415. })(BABYLON || (BABYLON = {}));
  52416. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52417. var BABYLON;
  52418. (function (BABYLON) {
  52419. var FilesInput = /** @class */ (function () {
  52420. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52421. this.onProcessFileCallback = function () { return true; };
  52422. this._engine = engine;
  52423. this._currentScene = scene;
  52424. this._sceneLoadedCallback = sceneLoadedCallback;
  52425. this._progressCallback = progressCallback;
  52426. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52427. this._textureLoadingCallback = textureLoadingCallback;
  52428. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52429. this._onReloadCallback = onReloadCallback;
  52430. this._errorCallback = errorCallback;
  52431. }
  52432. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52433. var _this = this;
  52434. if (elementToMonitor) {
  52435. this._elementToMonitor = elementToMonitor;
  52436. this._dragEnterHandler = function (e) { _this.drag(e); };
  52437. this._dragOverHandler = function (e) { _this.drag(e); };
  52438. this._dropHandler = function (e) { _this.drop(e); };
  52439. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52440. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52441. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52442. }
  52443. };
  52444. FilesInput.prototype.dispose = function () {
  52445. if (!this._elementToMonitor) {
  52446. return;
  52447. }
  52448. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52449. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52450. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52451. };
  52452. FilesInput.prototype.renderFunction = function () {
  52453. if (this._additionalRenderLoopLogicCallback) {
  52454. this._additionalRenderLoopLogicCallback();
  52455. }
  52456. if (this._currentScene) {
  52457. if (this._textureLoadingCallback) {
  52458. var remaining = this._currentScene.getWaitingItemsCount();
  52459. if (remaining > 0) {
  52460. this._textureLoadingCallback(remaining);
  52461. }
  52462. }
  52463. this._currentScene.render();
  52464. }
  52465. };
  52466. FilesInput.prototype.drag = function (e) {
  52467. e.stopPropagation();
  52468. e.preventDefault();
  52469. };
  52470. FilesInput.prototype.drop = function (eventDrop) {
  52471. eventDrop.stopPropagation();
  52472. eventDrop.preventDefault();
  52473. this.loadFiles(eventDrop);
  52474. };
  52475. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52476. var _this = this;
  52477. var reader = folder.createReader();
  52478. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52479. reader.readEntries(function (entries) {
  52480. remaining.count += entries.length;
  52481. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52482. var entry = entries_1[_i];
  52483. if (entry.isFile) {
  52484. entry.file(function (file) {
  52485. file.correctName = relativePath + file.name;
  52486. files.push(file);
  52487. if (--remaining.count === 0) {
  52488. callback();
  52489. }
  52490. });
  52491. }
  52492. else if (entry.isDirectory) {
  52493. _this._traverseFolder(entry, files, remaining, callback);
  52494. }
  52495. }
  52496. if (--remaining.count) {
  52497. callback();
  52498. }
  52499. });
  52500. };
  52501. FilesInput.prototype._processFiles = function (files) {
  52502. var skippedFiles = 0;
  52503. for (var i = 0; i < files.length; i++) {
  52504. var name = files[i].correctName.toLowerCase();
  52505. var extension = name.split('.').pop();
  52506. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52507. skippedFiles++;
  52508. continue;
  52509. }
  52510. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52511. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52512. this._sceneFileToLoad = files[i];
  52513. }
  52514. else {
  52515. FilesInput.FilesToLoad[name] = files[i];
  52516. }
  52517. }
  52518. if (this._onReloadCallback) {
  52519. this._onReloadCallback(this._sceneFileToLoad);
  52520. }
  52521. else if (skippedFiles < files.length) {
  52522. this.reload();
  52523. }
  52524. };
  52525. FilesInput.prototype.loadFiles = function (event) {
  52526. var _this = this;
  52527. if (this._startingProcessingFilesCallback)
  52528. this._startingProcessingFilesCallback();
  52529. // Handling data transfer via drag'n'drop
  52530. if (event && event.dataTransfer && event.dataTransfer.files) {
  52531. this._filesToLoad = event.dataTransfer.files;
  52532. }
  52533. // Handling files from input files
  52534. if (event && event.target && event.target.files) {
  52535. this._filesToLoad = event.target.files;
  52536. }
  52537. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52538. var files_1 = new Array();
  52539. var folders = [];
  52540. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52541. for (var i = 0; i < this._filesToLoad.length; i++) {
  52542. var fileToLoad = this._filesToLoad[i];
  52543. var name_1 = fileToLoad.name.toLowerCase();
  52544. var entry = void 0;
  52545. fileToLoad.correctName = name_1;
  52546. if (items) {
  52547. var item = items[i];
  52548. if (item.getAsEntry) {
  52549. entry = item.getAsEntry();
  52550. }
  52551. else if (item.webkitGetAsEntry) {
  52552. entry = item.webkitGetAsEntry();
  52553. }
  52554. }
  52555. if (!entry) {
  52556. files_1.push(fileToLoad);
  52557. }
  52558. else {
  52559. if (entry.isDirectory) {
  52560. folders.push(entry);
  52561. }
  52562. else {
  52563. files_1.push(fileToLoad);
  52564. }
  52565. }
  52566. }
  52567. if (folders.length === 0) {
  52568. this._processFiles(files_1);
  52569. }
  52570. else {
  52571. var remaining = { count: folders.length };
  52572. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  52573. var folder = folders_1[_i];
  52574. this._traverseFolder(folder, files_1, remaining, function () {
  52575. _this._processFiles(files_1);
  52576. });
  52577. }
  52578. }
  52579. }
  52580. };
  52581. FilesInput.prototype.reload = function () {
  52582. var _this = this;
  52583. // If a ".babylon" file has been provided
  52584. if (this._sceneFileToLoad) {
  52585. if (this._currentScene) {
  52586. if (BABYLON.Tools.errorsCount > 0) {
  52587. BABYLON.Tools.ClearLogCache();
  52588. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  52589. }
  52590. this._engine.stopRenderLoop();
  52591. this._currentScene.dispose();
  52592. }
  52593. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  52594. _this._currentScene = newScene;
  52595. if (_this._sceneLoadedCallback) {
  52596. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  52597. }
  52598. // Wait for textures and shaders to be ready
  52599. _this._currentScene.executeWhenReady(function () {
  52600. _this._engine.runRenderLoop(function () {
  52601. _this.renderFunction();
  52602. });
  52603. });
  52604. }, function (progress) {
  52605. if (_this._progressCallback) {
  52606. _this._progressCallback(progress);
  52607. }
  52608. }, function (scene, message) {
  52609. _this._currentScene = scene;
  52610. if (_this._errorCallback) {
  52611. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  52612. }
  52613. });
  52614. }
  52615. else {
  52616. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  52617. }
  52618. };
  52619. FilesInput.FilesToLoad = {};
  52620. return FilesInput;
  52621. }());
  52622. BABYLON.FilesInput = FilesInput;
  52623. })(BABYLON || (BABYLON = {}));
  52624. //# sourceMappingURL=babylon.filesInput.js.map
  52625. var BABYLON;
  52626. (function (BABYLON) {
  52627. /**
  52628. * This class implement a typical dictionary using a string as key and the generic type T as value.
  52629. * The underlying implementation relies on an associative array to ensure the best performances.
  52630. * The value can be anything including 'null' but except 'undefined'
  52631. */
  52632. var StringDictionary = /** @class */ (function () {
  52633. function StringDictionary() {
  52634. this._count = 0;
  52635. this._data = {};
  52636. }
  52637. /**
  52638. * This will clear this dictionary and copy the content from the 'source' one.
  52639. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  52640. * @param source the dictionary to take the content from and copy to this dictionary
  52641. */
  52642. StringDictionary.prototype.copyFrom = function (source) {
  52643. var _this = this;
  52644. this.clear();
  52645. source.forEach(function (t, v) { return _this.add(t, v); });
  52646. };
  52647. /**
  52648. * Get a value based from its key
  52649. * @param key the given key to get the matching value from
  52650. * @return the value if found, otherwise undefined is returned
  52651. */
  52652. StringDictionary.prototype.get = function (key) {
  52653. var val = this._data[key];
  52654. if (val !== undefined) {
  52655. return val;
  52656. }
  52657. return undefined;
  52658. };
  52659. /**
  52660. * Get a value from its key or add it if it doesn't exist.
  52661. * This method will ensure you that a given key/data will be present in the dictionary.
  52662. * @param key the given key to get the matching value from
  52663. * @param factory the factory that will create the value if the key is not present in the dictionary.
  52664. * The factory will only be invoked if there's no data for the given key.
  52665. * @return the value corresponding to the key.
  52666. */
  52667. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  52668. var val = this.get(key);
  52669. if (val !== undefined) {
  52670. return val;
  52671. }
  52672. val = factory(key);
  52673. if (val) {
  52674. this.add(key, val);
  52675. }
  52676. return val;
  52677. };
  52678. /**
  52679. * Get a value from its key if present in the dictionary otherwise add it
  52680. * @param key the key to get the value from
  52681. * @param val if there's no such key/value pair in the dictionary add it with this value
  52682. * @return the value corresponding to the key
  52683. */
  52684. StringDictionary.prototype.getOrAdd = function (key, val) {
  52685. var curVal = this.get(key);
  52686. if (curVal !== undefined) {
  52687. return curVal;
  52688. }
  52689. this.add(key, val);
  52690. return val;
  52691. };
  52692. /**
  52693. * Check if there's a given key in the dictionary
  52694. * @param key the key to check for
  52695. * @return true if the key is present, false otherwise
  52696. */
  52697. StringDictionary.prototype.contains = function (key) {
  52698. return this._data[key] !== undefined;
  52699. };
  52700. /**
  52701. * Add a new key and its corresponding value
  52702. * @param key the key to add
  52703. * @param value the value corresponding to the key
  52704. * @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
  52705. */
  52706. StringDictionary.prototype.add = function (key, value) {
  52707. if (this._data[key] !== undefined) {
  52708. return false;
  52709. }
  52710. this._data[key] = value;
  52711. ++this._count;
  52712. return true;
  52713. };
  52714. StringDictionary.prototype.set = function (key, value) {
  52715. if (this._data[key] === undefined) {
  52716. return false;
  52717. }
  52718. this._data[key] = value;
  52719. return true;
  52720. };
  52721. /**
  52722. * Get the element of the given key and remove it from the dictionary
  52723. * @param key
  52724. */
  52725. StringDictionary.prototype.getAndRemove = function (key) {
  52726. var val = this.get(key);
  52727. if (val !== undefined) {
  52728. delete this._data[key];
  52729. --this._count;
  52730. return val;
  52731. }
  52732. return null;
  52733. };
  52734. /**
  52735. * Remove a key/value from the dictionary.
  52736. * @param key the key to remove
  52737. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  52738. */
  52739. StringDictionary.prototype.remove = function (key) {
  52740. if (this.contains(key)) {
  52741. delete this._data[key];
  52742. --this._count;
  52743. return true;
  52744. }
  52745. return false;
  52746. };
  52747. /**
  52748. * Clear the whole content of the dictionary
  52749. */
  52750. StringDictionary.prototype.clear = function () {
  52751. this._data = {};
  52752. this._count = 0;
  52753. };
  52754. Object.defineProperty(StringDictionary.prototype, "count", {
  52755. get: function () {
  52756. return this._count;
  52757. },
  52758. enumerable: true,
  52759. configurable: true
  52760. });
  52761. /**
  52762. * Execute a callback on each key/val of the dictionary.
  52763. * Note that you can remove any element in this dictionary in the callback implementation
  52764. * @param callback the callback to execute on a given key/value pair
  52765. */
  52766. StringDictionary.prototype.forEach = function (callback) {
  52767. for (var cur in this._data) {
  52768. var val = this._data[cur];
  52769. callback(cur, val);
  52770. }
  52771. };
  52772. /**
  52773. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  52774. * If the callback returns null or undefined the method will iterate to the next key/value pair
  52775. * Note that you can remove any element in this dictionary in the callback implementation
  52776. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  52777. */
  52778. StringDictionary.prototype.first = function (callback) {
  52779. for (var cur in this._data) {
  52780. var val = this._data[cur];
  52781. var res = callback(cur, val);
  52782. if (res) {
  52783. return res;
  52784. }
  52785. }
  52786. return null;
  52787. };
  52788. return StringDictionary;
  52789. }());
  52790. BABYLON.StringDictionary = StringDictionary;
  52791. })(BABYLON || (BABYLON = {}));
  52792. //# sourceMappingURL=babylon.stringDictionary.js.map
  52793. var BABYLON;
  52794. (function (BABYLON) {
  52795. var Tags = /** @class */ (function () {
  52796. function Tags() {
  52797. }
  52798. Tags.EnableFor = function (obj) {
  52799. obj._tags = obj._tags || {};
  52800. obj.hasTags = function () {
  52801. return Tags.HasTags(obj);
  52802. };
  52803. obj.addTags = function (tagsString) {
  52804. return Tags.AddTagsTo(obj, tagsString);
  52805. };
  52806. obj.removeTags = function (tagsString) {
  52807. return Tags.RemoveTagsFrom(obj, tagsString);
  52808. };
  52809. obj.matchesTagsQuery = function (tagsQuery) {
  52810. return Tags.MatchesQuery(obj, tagsQuery);
  52811. };
  52812. };
  52813. Tags.DisableFor = function (obj) {
  52814. delete obj._tags;
  52815. delete obj.hasTags;
  52816. delete obj.addTags;
  52817. delete obj.removeTags;
  52818. delete obj.matchesTagsQuery;
  52819. };
  52820. Tags.HasTags = function (obj) {
  52821. if (!obj._tags) {
  52822. return false;
  52823. }
  52824. return !BABYLON.Tools.IsEmpty(obj._tags);
  52825. };
  52826. Tags.GetTags = function (obj, asString) {
  52827. if (asString === void 0) { asString = true; }
  52828. if (!obj._tags) {
  52829. return null;
  52830. }
  52831. if (asString) {
  52832. var tagsArray = [];
  52833. for (var tag in obj._tags) {
  52834. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  52835. tagsArray.push(tag);
  52836. }
  52837. }
  52838. return tagsArray.join(" ");
  52839. }
  52840. else {
  52841. return obj._tags;
  52842. }
  52843. };
  52844. // the tags 'true' and 'false' are reserved and cannot be used as tags
  52845. // a tag cannot start with '||', '&&', and '!'
  52846. // it cannot contain whitespaces
  52847. Tags.AddTagsTo = function (obj, tagsString) {
  52848. if (!tagsString) {
  52849. return;
  52850. }
  52851. if (typeof tagsString !== "string") {
  52852. return;
  52853. }
  52854. var tags = tagsString.split(" ");
  52855. tags.forEach(function (tag, index, array) {
  52856. Tags._AddTagTo(obj, tag);
  52857. });
  52858. };
  52859. Tags._AddTagTo = function (obj, tag) {
  52860. tag = tag.trim();
  52861. if (tag === "" || tag === "true" || tag === "false") {
  52862. return;
  52863. }
  52864. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  52865. return;
  52866. }
  52867. Tags.EnableFor(obj);
  52868. obj._tags[tag] = true;
  52869. };
  52870. Tags.RemoveTagsFrom = function (obj, tagsString) {
  52871. if (!Tags.HasTags(obj)) {
  52872. return;
  52873. }
  52874. var tags = tagsString.split(" ");
  52875. for (var t in tags) {
  52876. Tags._RemoveTagFrom(obj, tags[t]);
  52877. }
  52878. };
  52879. Tags._RemoveTagFrom = function (obj, tag) {
  52880. delete obj._tags[tag];
  52881. };
  52882. Tags.MatchesQuery = function (obj, tagsQuery) {
  52883. if (tagsQuery === undefined) {
  52884. return true;
  52885. }
  52886. if (tagsQuery === "") {
  52887. return Tags.HasTags(obj);
  52888. }
  52889. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  52890. };
  52891. return Tags;
  52892. }());
  52893. BABYLON.Tags = Tags;
  52894. })(BABYLON || (BABYLON = {}));
  52895. //# sourceMappingURL=babylon.tags.js.map
  52896. var BABYLON;
  52897. (function (BABYLON) {
  52898. var Internals;
  52899. (function (Internals) {
  52900. var AndOrNotEvaluator = /** @class */ (function () {
  52901. function AndOrNotEvaluator() {
  52902. }
  52903. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  52904. if (!query.match(/\([^\(\)]*\)/g)) {
  52905. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  52906. }
  52907. else {
  52908. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  52909. // remove parenthesis
  52910. r = r.slice(1, r.length - 1);
  52911. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  52912. });
  52913. }
  52914. if (query === "true") {
  52915. return true;
  52916. }
  52917. if (query === "false") {
  52918. return false;
  52919. }
  52920. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  52921. };
  52922. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  52923. evaluateCallback = evaluateCallback || (function (r) {
  52924. return r === "true" ? true : false;
  52925. });
  52926. var result;
  52927. var or = parenthesisContent.split("||");
  52928. for (var i in or) {
  52929. if (or.hasOwnProperty(i)) {
  52930. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  52931. var and = ori.split("&&");
  52932. if (and.length > 1) {
  52933. for (var j = 0; j < and.length; ++j) {
  52934. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  52935. if (andj !== "true" && andj !== "false") {
  52936. if (andj[0] === "!") {
  52937. result = !evaluateCallback(andj.substring(1));
  52938. }
  52939. else {
  52940. result = evaluateCallback(andj);
  52941. }
  52942. }
  52943. else {
  52944. result = andj === "true" ? true : false;
  52945. }
  52946. if (!result) {
  52947. ori = "false";
  52948. break;
  52949. }
  52950. }
  52951. }
  52952. if (result || ori === "true") {
  52953. result = true;
  52954. break;
  52955. }
  52956. // result equals false (or undefined)
  52957. if (ori !== "true" && ori !== "false") {
  52958. if (ori[0] === "!") {
  52959. result = !evaluateCallback(ori.substring(1));
  52960. }
  52961. else {
  52962. result = evaluateCallback(ori);
  52963. }
  52964. }
  52965. else {
  52966. result = ori === "true" ? true : false;
  52967. }
  52968. }
  52969. }
  52970. // the whole parenthesis scope is replaced by 'true' or 'false'
  52971. return result ? "true" : "false";
  52972. };
  52973. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  52974. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  52975. // remove whitespaces
  52976. r = r.replace(/[\s]/g, function () { return ""; });
  52977. return r.length % 2 ? "!" : "";
  52978. });
  52979. booleanString = booleanString.trim();
  52980. if (booleanString === "!true") {
  52981. booleanString = "false";
  52982. }
  52983. else if (booleanString === "!false") {
  52984. booleanString = "true";
  52985. }
  52986. return booleanString;
  52987. };
  52988. return AndOrNotEvaluator;
  52989. }());
  52990. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  52991. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52992. })(BABYLON || (BABYLON = {}));
  52993. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  52994. var BABYLON;
  52995. (function (BABYLON) {
  52996. var Database = /** @class */ (function () {
  52997. function Database(urlToScene, callbackManifestChecked) {
  52998. // Handling various flavors of prefixed version of IndexedDB
  52999. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53000. this.callbackManifestChecked = callbackManifestChecked;
  53001. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53002. this.db = null;
  53003. this._enableSceneOffline = false;
  53004. this._enableTexturesOffline = false;
  53005. this.manifestVersionFound = 0;
  53006. this.mustUpdateRessources = false;
  53007. this.hasReachedQuota = false;
  53008. if (!Database.IDBStorageEnabled) {
  53009. this.callbackManifestChecked(true);
  53010. }
  53011. else {
  53012. this.checkManifestFile();
  53013. }
  53014. }
  53015. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53016. get: function () {
  53017. return this._enableSceneOffline;
  53018. },
  53019. enumerable: true,
  53020. configurable: true
  53021. });
  53022. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53023. get: function () {
  53024. return this._enableTexturesOffline;
  53025. },
  53026. enumerable: true,
  53027. configurable: true
  53028. });
  53029. Database.prototype.checkManifestFile = function () {
  53030. var _this = this;
  53031. var noManifestFile = function () {
  53032. _this._enableSceneOffline = false;
  53033. _this._enableTexturesOffline = false;
  53034. _this.callbackManifestChecked(false);
  53035. };
  53036. var timeStampUsed = false;
  53037. var manifestURL = this.currentSceneUrl + ".manifest";
  53038. var xhr = new XMLHttpRequest();
  53039. if (navigator.onLine) {
  53040. // Adding a timestamp to by-pass browsers' cache
  53041. timeStampUsed = true;
  53042. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53043. }
  53044. xhr.open("GET", manifestURL, true);
  53045. xhr.addEventListener("load", function () {
  53046. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53047. try {
  53048. var manifestFile = JSON.parse(xhr.response);
  53049. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53050. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53051. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53052. _this.manifestVersionFound = manifestFile.version;
  53053. }
  53054. if (_this.callbackManifestChecked) {
  53055. _this.callbackManifestChecked(true);
  53056. }
  53057. }
  53058. catch (ex) {
  53059. noManifestFile();
  53060. }
  53061. }
  53062. else {
  53063. noManifestFile();
  53064. }
  53065. }, false);
  53066. xhr.addEventListener("error", function (event) {
  53067. if (timeStampUsed) {
  53068. timeStampUsed = false;
  53069. // Let's retry without the timeStamp
  53070. // It could fail when coupled with HTML5 Offline API
  53071. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53072. xhr.open("GET", retryManifestURL, true);
  53073. xhr.send();
  53074. }
  53075. else {
  53076. noManifestFile();
  53077. }
  53078. }, false);
  53079. try {
  53080. xhr.send();
  53081. }
  53082. catch (ex) {
  53083. BABYLON.Tools.Error("Error on XHR send request.");
  53084. this.callbackManifestChecked(false);
  53085. }
  53086. };
  53087. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53088. var _this = this;
  53089. function handleError() {
  53090. that.isSupported = false;
  53091. if (errorCallback)
  53092. errorCallback();
  53093. }
  53094. var that = this;
  53095. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53096. // Your browser doesn't support IndexedDB
  53097. this.isSupported = false;
  53098. if (errorCallback)
  53099. errorCallback();
  53100. }
  53101. else {
  53102. // If the DB hasn't been opened or created yet
  53103. if (!this.db) {
  53104. this.hasReachedQuota = false;
  53105. this.isSupported = true;
  53106. var request = this.idbFactory.open("babylonjs", 1);
  53107. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53108. request.onerror = function (event) {
  53109. handleError();
  53110. };
  53111. // executes when a version change transaction cannot complete due to other active transactions
  53112. request.onblocked = function (event) {
  53113. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53114. handleError();
  53115. };
  53116. // DB has been opened successfully
  53117. request.onsuccess = function (event) {
  53118. _this.db = request.result;
  53119. successCallback();
  53120. };
  53121. // Initialization of the DB. Creating Scenes & Textures stores
  53122. request.onupgradeneeded = function (event) {
  53123. _this.db = (event.target).result;
  53124. if (_this.db) {
  53125. try {
  53126. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53127. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53128. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53129. }
  53130. catch (ex) {
  53131. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53132. handleError();
  53133. }
  53134. }
  53135. };
  53136. }
  53137. else {
  53138. if (successCallback)
  53139. successCallback();
  53140. }
  53141. }
  53142. };
  53143. Database.prototype.loadImageFromDB = function (url, image) {
  53144. var _this = this;
  53145. var completeURL = Database.ReturnFullUrlLocation(url);
  53146. var saveAndLoadImage = function () {
  53147. if (!_this.hasReachedQuota && _this.db !== null) {
  53148. // the texture is not yet in the DB, let's try to save it
  53149. _this._saveImageIntoDBAsync(completeURL, image);
  53150. }
  53151. else {
  53152. image.src = url;
  53153. }
  53154. };
  53155. if (!this.mustUpdateRessources) {
  53156. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53157. }
  53158. else {
  53159. saveAndLoadImage();
  53160. }
  53161. };
  53162. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53163. if (this.isSupported && this.db !== null) {
  53164. var texture;
  53165. var transaction = this.db.transaction(["textures"]);
  53166. transaction.onabort = function (event) {
  53167. image.src = url;
  53168. };
  53169. transaction.oncomplete = function (event) {
  53170. var blobTextureURL;
  53171. if (texture) {
  53172. var URL = window.URL || window.webkitURL;
  53173. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53174. image.onerror = function () {
  53175. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53176. image.src = url;
  53177. };
  53178. image.src = blobTextureURL;
  53179. }
  53180. else {
  53181. notInDBCallback();
  53182. }
  53183. };
  53184. var getRequest = transaction.objectStore("textures").get(url);
  53185. getRequest.onsuccess = function (event) {
  53186. texture = (event.target).result;
  53187. };
  53188. getRequest.onerror = function (event) {
  53189. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53190. image.src = url;
  53191. };
  53192. }
  53193. else {
  53194. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53195. image.src = url;
  53196. }
  53197. };
  53198. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53199. var _this = this;
  53200. if (this.isSupported) {
  53201. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53202. var generateBlobUrl = function () {
  53203. var blobTextureURL;
  53204. if (blob) {
  53205. var URL = window.URL || window.webkitURL;
  53206. try {
  53207. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53208. }
  53209. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53210. catch (ex) {
  53211. blobTextureURL = URL.createObjectURL(blob);
  53212. }
  53213. }
  53214. if (blobTextureURL) {
  53215. image.src = blobTextureURL;
  53216. }
  53217. };
  53218. if (Database.IsUASupportingBlobStorage) {
  53219. var xhr = new XMLHttpRequest(), blob;
  53220. xhr.open("GET", url, true);
  53221. xhr.responseType = "blob";
  53222. xhr.addEventListener("load", function () {
  53223. if (xhr.status === 200 && _this.db) {
  53224. // Blob as response (XHR2)
  53225. blob = xhr.response;
  53226. var transaction = _this.db.transaction(["textures"], "readwrite");
  53227. // the transaction could abort because of a QuotaExceededError error
  53228. transaction.onabort = function (event) {
  53229. try {
  53230. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53231. var srcElement = (event.srcElement || event.target);
  53232. var error = srcElement.error;
  53233. if (error && error.name === "QuotaExceededError") {
  53234. _this.hasReachedQuota = true;
  53235. }
  53236. }
  53237. catch (ex) { }
  53238. generateBlobUrl();
  53239. };
  53240. transaction.oncomplete = function (event) {
  53241. generateBlobUrl();
  53242. };
  53243. var newTexture = { textureUrl: url, data: blob };
  53244. try {
  53245. // Put the blob into the dabase
  53246. var addRequest = transaction.objectStore("textures").put(newTexture);
  53247. addRequest.onsuccess = function (event) {
  53248. };
  53249. addRequest.onerror = function (event) {
  53250. generateBlobUrl();
  53251. };
  53252. }
  53253. catch (ex) {
  53254. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53255. if (ex.code === 25) {
  53256. Database.IsUASupportingBlobStorage = false;
  53257. }
  53258. image.src = url;
  53259. }
  53260. }
  53261. else {
  53262. image.src = url;
  53263. }
  53264. }, false);
  53265. xhr.addEventListener("error", function (event) {
  53266. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53267. image.src = url;
  53268. }, false);
  53269. xhr.send();
  53270. }
  53271. else {
  53272. image.src = url;
  53273. }
  53274. }
  53275. else {
  53276. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53277. image.src = url;
  53278. }
  53279. };
  53280. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53281. var _this = this;
  53282. var updateVersion = function () {
  53283. // the version is not yet in the DB or we need to update it
  53284. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53285. };
  53286. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53287. };
  53288. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53289. var _this = this;
  53290. if (this.isSupported && this.db) {
  53291. var version;
  53292. try {
  53293. var transaction = this.db.transaction(["versions"]);
  53294. transaction.oncomplete = function (event) {
  53295. if (version) {
  53296. // If the version in the JSON file is > than the version in DB
  53297. if (_this.manifestVersionFound > version.data) {
  53298. _this.mustUpdateRessources = true;
  53299. updateInDBCallback();
  53300. }
  53301. else {
  53302. callback(version.data);
  53303. }
  53304. }
  53305. else {
  53306. _this.mustUpdateRessources = true;
  53307. updateInDBCallback();
  53308. }
  53309. };
  53310. transaction.onabort = function (event) {
  53311. callback(-1);
  53312. };
  53313. var getRequest = transaction.objectStore("versions").get(url);
  53314. getRequest.onsuccess = function (event) {
  53315. version = (event.target).result;
  53316. };
  53317. getRequest.onerror = function (event) {
  53318. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53319. callback(-1);
  53320. };
  53321. }
  53322. catch (ex) {
  53323. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53324. callback(-1);
  53325. }
  53326. }
  53327. else {
  53328. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53329. callback(-1);
  53330. }
  53331. };
  53332. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53333. var _this = this;
  53334. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53335. try {
  53336. // Open a transaction to the database
  53337. var transaction = this.db.transaction(["versions"], "readwrite");
  53338. // the transaction could abort because of a QuotaExceededError error
  53339. transaction.onabort = function (event) {
  53340. try {
  53341. var error = event.srcElement['error'];
  53342. if (error && error.name === "QuotaExceededError") {
  53343. _this.hasReachedQuota = true;
  53344. }
  53345. }
  53346. catch (ex) { }
  53347. callback(-1);
  53348. };
  53349. transaction.oncomplete = function (event) {
  53350. callback(_this.manifestVersionFound);
  53351. };
  53352. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53353. // Put the scene into the database
  53354. var addRequest = transaction.objectStore("versions").put(newVersion);
  53355. addRequest.onsuccess = function (event) {
  53356. };
  53357. addRequest.onerror = function (event) {
  53358. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53359. };
  53360. }
  53361. catch (ex) {
  53362. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53363. callback(-1);
  53364. }
  53365. }
  53366. else {
  53367. callback(-1);
  53368. }
  53369. };
  53370. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53371. var _this = this;
  53372. var completeUrl = Database.ReturnFullUrlLocation(url);
  53373. var saveAndLoadFile = function () {
  53374. // the scene is not yet in the DB, let's try to save it
  53375. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53376. };
  53377. this._checkVersionFromDB(completeUrl, function (version) {
  53378. if (version !== -1) {
  53379. if (!_this.mustUpdateRessources) {
  53380. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53381. }
  53382. else {
  53383. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53384. }
  53385. }
  53386. else {
  53387. if (errorCallback) {
  53388. errorCallback();
  53389. }
  53390. }
  53391. });
  53392. };
  53393. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53394. if (this.isSupported && this.db) {
  53395. var targetStore;
  53396. if (url.indexOf(".babylon") !== -1) {
  53397. targetStore = "scenes";
  53398. }
  53399. else {
  53400. targetStore = "textures";
  53401. }
  53402. var file;
  53403. var transaction = this.db.transaction([targetStore]);
  53404. transaction.oncomplete = function (event) {
  53405. if (file) {
  53406. callback(file.data);
  53407. }
  53408. else {
  53409. notInDBCallback();
  53410. }
  53411. };
  53412. transaction.onabort = function (event) {
  53413. notInDBCallback();
  53414. };
  53415. var getRequest = transaction.objectStore(targetStore).get(url);
  53416. getRequest.onsuccess = function (event) {
  53417. file = (event.target).result;
  53418. };
  53419. getRequest.onerror = function (event) {
  53420. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53421. notInDBCallback();
  53422. };
  53423. }
  53424. else {
  53425. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53426. callback();
  53427. }
  53428. };
  53429. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53430. var _this = this;
  53431. if (this.isSupported) {
  53432. var targetStore;
  53433. if (url.indexOf(".babylon") !== -1) {
  53434. targetStore = "scenes";
  53435. }
  53436. else {
  53437. targetStore = "textures";
  53438. }
  53439. // Create XHR
  53440. var xhr = new XMLHttpRequest();
  53441. var fileData;
  53442. xhr.open("GET", url, true);
  53443. if (useArrayBuffer) {
  53444. xhr.responseType = "arraybuffer";
  53445. }
  53446. if (progressCallback) {
  53447. xhr.onprogress = progressCallback;
  53448. }
  53449. xhr.addEventListener("load", function () {
  53450. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53451. // Blob as response (XHR2)
  53452. //fileData = xhr.responseText;
  53453. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53454. if (!_this.hasReachedQuota && _this.db) {
  53455. // Open a transaction to the database
  53456. var transaction = _this.db.transaction([targetStore], "readwrite");
  53457. // the transaction could abort because of a QuotaExceededError error
  53458. transaction.onabort = function (event) {
  53459. try {
  53460. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53461. var error = event.srcElement['error'];
  53462. if (error && error.name === "QuotaExceededError") {
  53463. _this.hasReachedQuota = true;
  53464. }
  53465. }
  53466. catch (ex) { }
  53467. callback(fileData);
  53468. };
  53469. transaction.oncomplete = function (event) {
  53470. callback(fileData);
  53471. };
  53472. var newFile;
  53473. if (targetStore === "scenes") {
  53474. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53475. }
  53476. else {
  53477. newFile = { textureUrl: url, data: fileData };
  53478. }
  53479. try {
  53480. // Put the scene into the database
  53481. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53482. addRequest.onsuccess = function (event) {
  53483. };
  53484. addRequest.onerror = function (event) {
  53485. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53486. };
  53487. }
  53488. catch (ex) {
  53489. callback(fileData);
  53490. }
  53491. }
  53492. else {
  53493. callback(fileData);
  53494. }
  53495. }
  53496. else {
  53497. callback();
  53498. }
  53499. }, false);
  53500. xhr.addEventListener("error", function (event) {
  53501. BABYLON.Tools.Error("error on XHR request.");
  53502. callback();
  53503. }, false);
  53504. xhr.send();
  53505. }
  53506. else {
  53507. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53508. callback();
  53509. }
  53510. };
  53511. Database.IsUASupportingBlobStorage = true;
  53512. Database.IDBStorageEnabled = true;
  53513. Database.parseURL = function (url) {
  53514. var a = document.createElement('a');
  53515. a.href = url;
  53516. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53517. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53518. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53519. return absLocation;
  53520. };
  53521. Database.ReturnFullUrlLocation = function (url) {
  53522. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53523. return (Database.parseURL(window.location.href) + url);
  53524. }
  53525. else {
  53526. return url;
  53527. }
  53528. };
  53529. return Database;
  53530. }());
  53531. BABYLON.Database = Database;
  53532. })(BABYLON || (BABYLON = {}));
  53533. //# sourceMappingURL=babylon.database.js.map
  53534. var BABYLON;
  53535. (function (BABYLON) {
  53536. var FresnelParameters = /** @class */ (function () {
  53537. function FresnelParameters() {
  53538. this._isEnabled = true;
  53539. this.leftColor = BABYLON.Color3.White();
  53540. this.rightColor = BABYLON.Color3.Black();
  53541. this.bias = 0;
  53542. this.power = 1;
  53543. }
  53544. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53545. get: function () {
  53546. return this._isEnabled;
  53547. },
  53548. set: function (value) {
  53549. if (this._isEnabled === value) {
  53550. return;
  53551. }
  53552. this._isEnabled = value;
  53553. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53554. },
  53555. enumerable: true,
  53556. configurable: true
  53557. });
  53558. FresnelParameters.prototype.clone = function () {
  53559. var newFresnelParameters = new FresnelParameters();
  53560. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  53561. return newFresnelParameters;
  53562. };
  53563. FresnelParameters.prototype.serialize = function () {
  53564. var serializationObject = {};
  53565. serializationObject.isEnabled = this.isEnabled;
  53566. serializationObject.leftColor = this.leftColor;
  53567. serializationObject.rightColor = this.rightColor;
  53568. serializationObject.bias = this.bias;
  53569. serializationObject.power = this.power;
  53570. return serializationObject;
  53571. };
  53572. FresnelParameters.Parse = function (parsedFresnelParameters) {
  53573. var fresnelParameters = new FresnelParameters();
  53574. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  53575. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  53576. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  53577. fresnelParameters.bias = parsedFresnelParameters.bias;
  53578. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  53579. return fresnelParameters;
  53580. };
  53581. return FresnelParameters;
  53582. }());
  53583. BABYLON.FresnelParameters = FresnelParameters;
  53584. })(BABYLON || (BABYLON = {}));
  53585. //# sourceMappingURL=babylon.fresnelParameters.js.map
  53586. var BABYLON;
  53587. (function (BABYLON) {
  53588. var MultiMaterial = /** @class */ (function (_super) {
  53589. __extends(MultiMaterial, _super);
  53590. function MultiMaterial(name, scene) {
  53591. var _this = _super.call(this, name, scene, true) || this;
  53592. scene.multiMaterials.push(_this);
  53593. _this.subMaterials = new Array();
  53594. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  53595. return _this;
  53596. }
  53597. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  53598. get: function () {
  53599. return this._subMaterials;
  53600. },
  53601. set: function (value) {
  53602. this._subMaterials = value;
  53603. this._hookArray(value);
  53604. },
  53605. enumerable: true,
  53606. configurable: true
  53607. });
  53608. MultiMaterial.prototype._hookArray = function (array) {
  53609. var _this = this;
  53610. var oldPush = array.push;
  53611. array.push = function () {
  53612. var items = [];
  53613. for (var _i = 0; _i < arguments.length; _i++) {
  53614. items[_i] = arguments[_i];
  53615. }
  53616. var result = oldPush.apply(array, items);
  53617. _this._markAllSubMeshesAsTexturesDirty();
  53618. return result;
  53619. };
  53620. var oldSplice = array.splice;
  53621. array.splice = function (index, deleteCount) {
  53622. var deleted = oldSplice.apply(array, [index, deleteCount]);
  53623. _this._markAllSubMeshesAsTexturesDirty();
  53624. return deleted;
  53625. };
  53626. };
  53627. // Properties
  53628. MultiMaterial.prototype.getSubMaterial = function (index) {
  53629. if (index < 0 || index >= this.subMaterials.length) {
  53630. return this.getScene().defaultMaterial;
  53631. }
  53632. return this.subMaterials[index];
  53633. };
  53634. MultiMaterial.prototype.getActiveTextures = function () {
  53635. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  53636. if (subMaterial) {
  53637. return subMaterial.getActiveTextures();
  53638. }
  53639. else {
  53640. return [];
  53641. }
  53642. }));
  53643. var _a;
  53644. };
  53645. // Methods
  53646. MultiMaterial.prototype.getClassName = function () {
  53647. return "MultiMaterial";
  53648. };
  53649. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  53650. for (var index = 0; index < this.subMaterials.length; index++) {
  53651. var subMaterial = this.subMaterials[index];
  53652. if (subMaterial) {
  53653. if (subMaterial.storeEffectOnSubMeshes) {
  53654. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  53655. return false;
  53656. }
  53657. continue;
  53658. }
  53659. if (!subMaterial.isReady(mesh)) {
  53660. return false;
  53661. }
  53662. }
  53663. }
  53664. return true;
  53665. };
  53666. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  53667. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  53668. for (var index = 0; index < this.subMaterials.length; index++) {
  53669. var subMaterial = null;
  53670. var current = this.subMaterials[index];
  53671. if (cloneChildren && current) {
  53672. subMaterial = current.clone(name + "-" + current.name);
  53673. }
  53674. else {
  53675. subMaterial = this.subMaterials[index];
  53676. }
  53677. newMultiMaterial.subMaterials.push(subMaterial);
  53678. }
  53679. return newMultiMaterial;
  53680. };
  53681. MultiMaterial.prototype.serialize = function () {
  53682. var serializationObject = {};
  53683. serializationObject.name = this.name;
  53684. serializationObject.id = this.id;
  53685. serializationObject.tags = BABYLON.Tags.GetTags(this);
  53686. serializationObject.materials = [];
  53687. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  53688. var subMat = this.subMaterials[matIndex];
  53689. if (subMat) {
  53690. serializationObject.materials.push(subMat.id);
  53691. }
  53692. else {
  53693. serializationObject.materials.push(null);
  53694. }
  53695. }
  53696. return serializationObject;
  53697. };
  53698. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53699. var scene = this.getScene();
  53700. if (!scene) {
  53701. return;
  53702. }
  53703. var index = scene.multiMaterials.indexOf(this);
  53704. if (index >= 0) {
  53705. scene.multiMaterials.splice(index, 1);
  53706. }
  53707. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53708. };
  53709. return MultiMaterial;
  53710. }(BABYLON.Material));
  53711. BABYLON.MultiMaterial = MultiMaterial;
  53712. })(BABYLON || (BABYLON = {}));
  53713. //# sourceMappingURL=babylon.multiMaterial.js.map
  53714. var BABYLON;
  53715. (function (BABYLON) {
  53716. var FreeCameraTouchInput = /** @class */ (function () {
  53717. function FreeCameraTouchInput() {
  53718. this._offsetX = null;
  53719. this._offsetY = null;
  53720. this._pointerCount = 0;
  53721. this._pointerPressed = new Array();
  53722. this.touchAngularSensibility = 200000.0;
  53723. this.touchMoveSensibility = 250.0;
  53724. }
  53725. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  53726. var _this = this;
  53727. var previousPosition = null;
  53728. if (this._pointerInput === undefined) {
  53729. this._onLostFocus = function (evt) {
  53730. _this._offsetX = null;
  53731. _this._offsetY = null;
  53732. };
  53733. this._pointerInput = function (p, s) {
  53734. var evt = p.event;
  53735. if (evt.pointerType === "mouse") {
  53736. return;
  53737. }
  53738. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  53739. if (!noPreventDefault) {
  53740. evt.preventDefault();
  53741. }
  53742. _this._pointerPressed.push(evt.pointerId);
  53743. if (_this._pointerPressed.length !== 1) {
  53744. return;
  53745. }
  53746. previousPosition = {
  53747. x: evt.clientX,
  53748. y: evt.clientY
  53749. };
  53750. }
  53751. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  53752. if (!noPreventDefault) {
  53753. evt.preventDefault();
  53754. }
  53755. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53756. if (index === -1) {
  53757. return;
  53758. }
  53759. _this._pointerPressed.splice(index, 1);
  53760. if (index != 0) {
  53761. return;
  53762. }
  53763. previousPosition = null;
  53764. _this._offsetX = null;
  53765. _this._offsetY = null;
  53766. }
  53767. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  53768. if (!noPreventDefault) {
  53769. evt.preventDefault();
  53770. }
  53771. if (!previousPosition) {
  53772. return;
  53773. }
  53774. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53775. if (index != 0) {
  53776. return;
  53777. }
  53778. _this._offsetX = evt.clientX - previousPosition.x;
  53779. _this._offsetY = -(evt.clientY - previousPosition.y);
  53780. }
  53781. };
  53782. }
  53783. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  53784. if (this._onLostFocus) {
  53785. element.addEventListener("blur", this._onLostFocus);
  53786. }
  53787. };
  53788. FreeCameraTouchInput.prototype.detachControl = function (element) {
  53789. if (this._pointerInput && element) {
  53790. if (this._observer) {
  53791. this.camera.getScene().onPointerObservable.remove(this._observer);
  53792. this._observer = null;
  53793. }
  53794. if (this._onLostFocus) {
  53795. element.removeEventListener("blur", this._onLostFocus);
  53796. this._onLostFocus = null;
  53797. }
  53798. this._pointerPressed = [];
  53799. this._offsetX = null;
  53800. this._offsetY = null;
  53801. this._pointerCount = 0;
  53802. }
  53803. };
  53804. FreeCameraTouchInput.prototype.checkInputs = function () {
  53805. if (this._offsetX && this._offsetY) {
  53806. var camera = this.camera;
  53807. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  53808. if (this._pointerPressed.length > 1) {
  53809. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  53810. }
  53811. else {
  53812. var speed = camera._computeLocalCameraSpeed();
  53813. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  53814. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  53815. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  53816. }
  53817. }
  53818. };
  53819. FreeCameraTouchInput.prototype.getClassName = function () {
  53820. return "FreeCameraTouchInput";
  53821. };
  53822. FreeCameraTouchInput.prototype.getSimpleName = function () {
  53823. return "touch";
  53824. };
  53825. __decorate([
  53826. BABYLON.serialize()
  53827. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  53828. __decorate([
  53829. BABYLON.serialize()
  53830. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  53831. return FreeCameraTouchInput;
  53832. }());
  53833. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  53834. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  53835. })(BABYLON || (BABYLON = {}));
  53836. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  53837. /// <reference path="babylon.freeCamera.ts" />
  53838. var BABYLON;
  53839. (function (BABYLON) {
  53840. // We're mainly based on the logic defined into the FreeCamera code
  53841. var TouchCamera = /** @class */ (function (_super) {
  53842. __extends(TouchCamera, _super);
  53843. //-- end properties for backward compatibility for inputs
  53844. function TouchCamera(name, position, scene) {
  53845. var _this = _super.call(this, name, position, scene) || this;
  53846. _this.inputs.addTouch();
  53847. _this._setupInputs();
  53848. return _this;
  53849. }
  53850. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  53851. //-- Begin properties for backward compatibility for inputs
  53852. get: function () {
  53853. var touch = this.inputs.attached["touch"];
  53854. if (touch)
  53855. return touch.touchAngularSensibility;
  53856. return 0;
  53857. },
  53858. set: function (value) {
  53859. var touch = this.inputs.attached["touch"];
  53860. if (touch)
  53861. touch.touchAngularSensibility = value;
  53862. },
  53863. enumerable: true,
  53864. configurable: true
  53865. });
  53866. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  53867. get: function () {
  53868. var touch = this.inputs.attached["touch"];
  53869. if (touch)
  53870. return touch.touchMoveSensibility;
  53871. return 0;
  53872. },
  53873. set: function (value) {
  53874. var touch = this.inputs.attached["touch"];
  53875. if (touch)
  53876. touch.touchMoveSensibility = value;
  53877. },
  53878. enumerable: true,
  53879. configurable: true
  53880. });
  53881. TouchCamera.prototype.getClassName = function () {
  53882. return "TouchCamera";
  53883. };
  53884. TouchCamera.prototype._setupInputs = function () {
  53885. var mouse = this.inputs.attached["mouse"];
  53886. if (mouse) {
  53887. mouse.touchEnabled = false;
  53888. }
  53889. };
  53890. return TouchCamera;
  53891. }(BABYLON.FreeCamera));
  53892. BABYLON.TouchCamera = TouchCamera;
  53893. })(BABYLON || (BABYLON = {}));
  53894. //# sourceMappingURL=babylon.touchCamera.js.map
  53895. var BABYLON;
  53896. (function (BABYLON) {
  53897. var ProceduralTexture = /** @class */ (function (_super) {
  53898. __extends(ProceduralTexture, _super);
  53899. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  53900. if (fallbackTexture === void 0) { fallbackTexture = null; }
  53901. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53902. if (isCube === void 0) { isCube = false; }
  53903. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53904. _this.isCube = isCube;
  53905. _this.isEnabled = true;
  53906. _this._currentRefreshId = -1;
  53907. _this._refreshRate = 1;
  53908. _this._vertexBuffers = {};
  53909. _this._uniforms = new Array();
  53910. _this._samplers = new Array();
  53911. _this._textures = {};
  53912. _this._floats = {};
  53913. _this._floatsArrays = {};
  53914. _this._colors3 = {};
  53915. _this._colors4 = {};
  53916. _this._vectors2 = {};
  53917. _this._vectors3 = {};
  53918. _this._matrices = {};
  53919. _this._fallbackTextureUsed = false;
  53920. scene._proceduralTextures.push(_this);
  53921. _this._engine = scene.getEngine();
  53922. _this.name = name;
  53923. _this.isRenderTarget = true;
  53924. _this._size = size;
  53925. _this._generateMipMaps = generateMipMaps;
  53926. _this.setFragment(fragment);
  53927. _this._fallbackTexture = fallbackTexture;
  53928. if (isCube) {
  53929. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  53930. _this.setFloat("face", 0);
  53931. }
  53932. else {
  53933. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  53934. }
  53935. // VBO
  53936. var vertices = [];
  53937. vertices.push(1, 1);
  53938. vertices.push(-1, 1);
  53939. vertices.push(-1, -1);
  53940. vertices.push(1, -1);
  53941. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  53942. _this._createIndexBuffer();
  53943. return _this;
  53944. }
  53945. ProceduralTexture.prototype._createIndexBuffer = function () {
  53946. var engine = this._engine;
  53947. // Indices
  53948. var indices = [];
  53949. indices.push(0);
  53950. indices.push(1);
  53951. indices.push(2);
  53952. indices.push(0);
  53953. indices.push(2);
  53954. indices.push(3);
  53955. this._indexBuffer = engine.createIndexBuffer(indices);
  53956. };
  53957. ProceduralTexture.prototype._rebuild = function () {
  53958. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53959. if (vb) {
  53960. vb._rebuild();
  53961. }
  53962. this._createIndexBuffer();
  53963. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  53964. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  53965. }
  53966. };
  53967. ProceduralTexture.prototype.reset = function () {
  53968. if (this._effect === undefined) {
  53969. return;
  53970. }
  53971. var engine = this._engine;
  53972. engine._releaseEffect(this._effect);
  53973. };
  53974. ProceduralTexture.prototype.isReady = function () {
  53975. var _this = this;
  53976. var engine = this._engine;
  53977. var shaders;
  53978. if (!this._fragment) {
  53979. return false;
  53980. }
  53981. if (this._fallbackTextureUsed) {
  53982. return true;
  53983. }
  53984. if (this._fragment.fragmentElement !== undefined) {
  53985. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  53986. }
  53987. else {
  53988. shaders = { vertex: "procedural", fragment: this._fragment };
  53989. }
  53990. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  53991. _this.releaseInternalTexture();
  53992. if (_this._fallbackTexture) {
  53993. _this._texture = _this._fallbackTexture._texture;
  53994. if (_this._texture) {
  53995. _this._texture.incrementReferences();
  53996. }
  53997. }
  53998. _this._fallbackTextureUsed = true;
  53999. });
  54000. return this._effect.isReady();
  54001. };
  54002. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54003. this._currentRefreshId = -1;
  54004. };
  54005. ProceduralTexture.prototype.setFragment = function (fragment) {
  54006. this._fragment = fragment;
  54007. };
  54008. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54009. get: function () {
  54010. return this._refreshRate;
  54011. },
  54012. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54013. set: function (value) {
  54014. this._refreshRate = value;
  54015. this.resetRefreshCounter();
  54016. },
  54017. enumerable: true,
  54018. configurable: true
  54019. });
  54020. ProceduralTexture.prototype._shouldRender = function () {
  54021. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54022. return false;
  54023. }
  54024. if (this._fallbackTextureUsed) {
  54025. return false;
  54026. }
  54027. if (this._currentRefreshId === -1) {
  54028. this._currentRefreshId = 1;
  54029. return true;
  54030. }
  54031. if (this.refreshRate === this._currentRefreshId) {
  54032. this._currentRefreshId = 1;
  54033. return true;
  54034. }
  54035. this._currentRefreshId++;
  54036. return false;
  54037. };
  54038. ProceduralTexture.prototype.getRenderSize = function () {
  54039. return this._size;
  54040. };
  54041. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54042. if (this._fallbackTextureUsed) {
  54043. return;
  54044. }
  54045. this.releaseInternalTexture();
  54046. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54047. };
  54048. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54049. if (this._uniforms.indexOf(uniformName) === -1) {
  54050. this._uniforms.push(uniformName);
  54051. }
  54052. };
  54053. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54054. if (this._samplers.indexOf(name) === -1) {
  54055. this._samplers.push(name);
  54056. }
  54057. this._textures[name] = texture;
  54058. return this;
  54059. };
  54060. ProceduralTexture.prototype.setFloat = function (name, value) {
  54061. this._checkUniform(name);
  54062. this._floats[name] = value;
  54063. return this;
  54064. };
  54065. ProceduralTexture.prototype.setFloats = function (name, value) {
  54066. this._checkUniform(name);
  54067. this._floatsArrays[name] = value;
  54068. return this;
  54069. };
  54070. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54071. this._checkUniform(name);
  54072. this._colors3[name] = value;
  54073. return this;
  54074. };
  54075. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54076. this._checkUniform(name);
  54077. this._colors4[name] = value;
  54078. return this;
  54079. };
  54080. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54081. this._checkUniform(name);
  54082. this._vectors2[name] = value;
  54083. return this;
  54084. };
  54085. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54086. this._checkUniform(name);
  54087. this._vectors3[name] = value;
  54088. return this;
  54089. };
  54090. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54091. this._checkUniform(name);
  54092. this._matrices[name] = value;
  54093. return this;
  54094. };
  54095. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54096. var scene = this.getScene();
  54097. if (!scene) {
  54098. return;
  54099. }
  54100. var engine = this._engine;
  54101. // Render
  54102. engine.enableEffect(this._effect);
  54103. engine.setState(false);
  54104. // Texture
  54105. for (var name in this._textures) {
  54106. this._effect.setTexture(name, this._textures[name]);
  54107. }
  54108. // Float
  54109. for (name in this._floats) {
  54110. this._effect.setFloat(name, this._floats[name]);
  54111. }
  54112. // Floats
  54113. for (name in this._floatsArrays) {
  54114. this._effect.setArray(name, this._floatsArrays[name]);
  54115. }
  54116. // Color3
  54117. for (name in this._colors3) {
  54118. this._effect.setColor3(name, this._colors3[name]);
  54119. }
  54120. // Color4
  54121. for (name in this._colors4) {
  54122. var color = this._colors4[name];
  54123. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54124. }
  54125. // Vector2
  54126. for (name in this._vectors2) {
  54127. this._effect.setVector2(name, this._vectors2[name]);
  54128. }
  54129. // Vector3
  54130. for (name in this._vectors3) {
  54131. this._effect.setVector3(name, this._vectors3[name]);
  54132. }
  54133. // Matrix
  54134. for (name in this._matrices) {
  54135. this._effect.setMatrix(name, this._matrices[name]);
  54136. }
  54137. if (!this._texture) {
  54138. return;
  54139. }
  54140. if (this.isCube) {
  54141. for (var face = 0; face < 6; face++) {
  54142. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54143. // VBOs
  54144. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54145. this._effect.setFloat("face", face);
  54146. // Clear
  54147. engine.clear(scene.clearColor, true, true, true);
  54148. // Draw order
  54149. engine.draw(true, 0, 6);
  54150. // Mipmaps
  54151. if (face === 5) {
  54152. engine.generateMipMapsForCubemap(this._texture);
  54153. }
  54154. }
  54155. }
  54156. else {
  54157. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54158. // VBOs
  54159. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54160. // Clear
  54161. engine.clear(scene.clearColor, true, true, true);
  54162. // Draw order
  54163. engine.draw(true, 0, 6);
  54164. }
  54165. // Unbind
  54166. engine.unBindFramebuffer(this._texture, this.isCube);
  54167. if (this.onGenerated) {
  54168. this.onGenerated();
  54169. }
  54170. };
  54171. ProceduralTexture.prototype.clone = function () {
  54172. var textureSize = this.getSize();
  54173. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54174. // Base texture
  54175. newTexture.hasAlpha = this.hasAlpha;
  54176. newTexture.level = this.level;
  54177. // RenderTarget Texture
  54178. newTexture.coordinatesMode = this.coordinatesMode;
  54179. return newTexture;
  54180. };
  54181. ProceduralTexture.prototype.dispose = function () {
  54182. var scene = this.getScene();
  54183. if (!scene) {
  54184. return;
  54185. }
  54186. var index = scene._proceduralTextures.indexOf(this);
  54187. if (index >= 0) {
  54188. scene._proceduralTextures.splice(index, 1);
  54189. }
  54190. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54191. if (vertexBuffer) {
  54192. vertexBuffer.dispose();
  54193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54194. }
  54195. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54196. this._indexBuffer = null;
  54197. }
  54198. _super.prototype.dispose.call(this);
  54199. };
  54200. return ProceduralTexture;
  54201. }(BABYLON.Texture));
  54202. BABYLON.ProceduralTexture = ProceduralTexture;
  54203. })(BABYLON || (BABYLON = {}));
  54204. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54205. /// <reference path="babylon.proceduralTexture.ts" />
  54206. var BABYLON;
  54207. (function (BABYLON) {
  54208. var CustomProceduralTexture = /** @class */ (function (_super) {
  54209. __extends(CustomProceduralTexture, _super);
  54210. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54211. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54212. _this._animate = true;
  54213. _this._time = 0;
  54214. _this._texturePath = texturePath;
  54215. //Try to load json
  54216. _this.loadJson(texturePath);
  54217. _this.refreshRate = 1;
  54218. return _this;
  54219. }
  54220. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54221. var _this = this;
  54222. var that = this;
  54223. function noConfigFile() {
  54224. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54225. try {
  54226. that.setFragment(that._texturePath);
  54227. }
  54228. catch (ex) {
  54229. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54230. }
  54231. }
  54232. var configFileUrl = jsonUrl + "/config.json";
  54233. var xhr = new XMLHttpRequest();
  54234. xhr.open("GET", configFileUrl, true);
  54235. xhr.addEventListener("load", function () {
  54236. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54237. try {
  54238. _this._config = JSON.parse(xhr.response);
  54239. _this.updateShaderUniforms();
  54240. _this.updateTextures();
  54241. _this.setFragment(_this._texturePath + "/custom");
  54242. _this._animate = _this._config.animate;
  54243. _this.refreshRate = _this._config.refreshrate;
  54244. }
  54245. catch (ex) {
  54246. noConfigFile();
  54247. }
  54248. }
  54249. else {
  54250. noConfigFile();
  54251. }
  54252. }, false);
  54253. xhr.addEventListener("error", function () {
  54254. noConfigFile();
  54255. }, false);
  54256. try {
  54257. xhr.send();
  54258. }
  54259. catch (ex) {
  54260. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54261. }
  54262. };
  54263. CustomProceduralTexture.prototype.isReady = function () {
  54264. if (!_super.prototype.isReady.call(this)) {
  54265. return false;
  54266. }
  54267. for (var name in this._textures) {
  54268. var texture = this._textures[name];
  54269. if (!texture.isReady()) {
  54270. return false;
  54271. }
  54272. }
  54273. return true;
  54274. };
  54275. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54276. var scene = this.getScene();
  54277. if (this._animate && scene) {
  54278. this._time += scene.getAnimationRatio() * 0.03;
  54279. this.updateShaderUniforms();
  54280. }
  54281. _super.prototype.render.call(this, useCameraPostProcess);
  54282. };
  54283. CustomProceduralTexture.prototype.updateTextures = function () {
  54284. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54285. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54286. }
  54287. };
  54288. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54289. if (this._config) {
  54290. for (var j = 0; j < this._config.uniforms.length; j++) {
  54291. var uniform = this._config.uniforms[j];
  54292. switch (uniform.type) {
  54293. case "float":
  54294. this.setFloat(uniform.name, uniform.value);
  54295. break;
  54296. case "color3":
  54297. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54298. break;
  54299. case "color4":
  54300. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54301. break;
  54302. case "vector2":
  54303. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54304. break;
  54305. case "vector3":
  54306. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54307. break;
  54308. }
  54309. }
  54310. }
  54311. this.setFloat("time", this._time);
  54312. };
  54313. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54314. get: function () {
  54315. return this._animate;
  54316. },
  54317. set: function (value) {
  54318. this._animate = value;
  54319. },
  54320. enumerable: true,
  54321. configurable: true
  54322. });
  54323. return CustomProceduralTexture;
  54324. }(BABYLON.ProceduralTexture));
  54325. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54326. })(BABYLON || (BABYLON = {}));
  54327. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54328. var BABYLON;
  54329. (function (BABYLON) {
  54330. var FreeCameraGamepadInput = /** @class */ (function () {
  54331. function FreeCameraGamepadInput() {
  54332. this.gamepadAngularSensibility = 200;
  54333. this.gamepadMoveSensibility = 40;
  54334. // private members
  54335. this._cameraTransform = BABYLON.Matrix.Identity();
  54336. this._deltaTransform = BABYLON.Vector3.Zero();
  54337. this._vector3 = BABYLON.Vector3.Zero();
  54338. this._vector2 = BABYLON.Vector2.Zero();
  54339. }
  54340. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54341. var _this = this;
  54342. var manager = this.camera.getScene().gamepadManager;
  54343. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54344. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54345. // prioritize XBOX gamepads.
  54346. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54347. _this.gamepad = gamepad;
  54348. }
  54349. }
  54350. });
  54351. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54352. if (_this.gamepad === gamepad) {
  54353. _this.gamepad = null;
  54354. }
  54355. });
  54356. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54357. };
  54358. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54359. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54360. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54361. this.gamepad = null;
  54362. };
  54363. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54364. if (this.gamepad && this.gamepad.leftStick) {
  54365. var camera = this.camera;
  54366. var LSValues = this.gamepad.leftStick;
  54367. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54368. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54369. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54370. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54371. var RSValues = this.gamepad.rightStick;
  54372. if (RSValues) {
  54373. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54374. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54375. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54376. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54377. }
  54378. else {
  54379. RSValues = { x: 0, y: 0 };
  54380. }
  54381. if (!camera.rotationQuaternion) {
  54382. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54383. }
  54384. else {
  54385. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54386. }
  54387. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54388. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54389. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54390. camera.cameraDirection.addInPlace(this._deltaTransform);
  54391. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54392. camera.cameraRotation.addInPlace(this._vector2);
  54393. }
  54394. };
  54395. FreeCameraGamepadInput.prototype.getClassName = function () {
  54396. return "FreeCameraGamepadInput";
  54397. };
  54398. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54399. return "gamepad";
  54400. };
  54401. __decorate([
  54402. BABYLON.serialize()
  54403. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54404. __decorate([
  54405. BABYLON.serialize()
  54406. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54407. return FreeCameraGamepadInput;
  54408. }());
  54409. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54410. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54411. })(BABYLON || (BABYLON = {}));
  54412. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54413. var BABYLON;
  54414. (function (BABYLON) {
  54415. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54416. function ArcRotateCameraGamepadInput() {
  54417. this.gamepadRotationSensibility = 80;
  54418. this.gamepadMoveSensibility = 40;
  54419. }
  54420. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54421. var _this = this;
  54422. var manager = this.camera.getScene().gamepadManager;
  54423. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54424. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54425. // prioritize XBOX gamepads.
  54426. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54427. _this.gamepad = gamepad;
  54428. }
  54429. }
  54430. });
  54431. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54432. if (_this.gamepad === gamepad) {
  54433. _this.gamepad = null;
  54434. }
  54435. });
  54436. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54437. };
  54438. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54439. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54440. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54441. this.gamepad = null;
  54442. };
  54443. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54444. if (this.gamepad) {
  54445. var camera = this.camera;
  54446. var RSValues = this.gamepad.rightStick;
  54447. if (RSValues) {
  54448. if (RSValues.x != 0) {
  54449. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54450. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54451. camera.inertialAlphaOffset += normalizedRX;
  54452. }
  54453. }
  54454. if (RSValues.y != 0) {
  54455. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54456. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54457. camera.inertialBetaOffset += normalizedRY;
  54458. }
  54459. }
  54460. }
  54461. var LSValues = this.gamepad.leftStick;
  54462. if (LSValues && LSValues.y != 0) {
  54463. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54464. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54465. this.camera.inertialRadiusOffset -= normalizedLY;
  54466. }
  54467. }
  54468. }
  54469. };
  54470. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54471. return "ArcRotateCameraGamepadInput";
  54472. };
  54473. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54474. return "gamepad";
  54475. };
  54476. __decorate([
  54477. BABYLON.serialize()
  54478. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54479. __decorate([
  54480. BABYLON.serialize()
  54481. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54482. return ArcRotateCameraGamepadInput;
  54483. }());
  54484. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54485. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54486. })(BABYLON || (BABYLON = {}));
  54487. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54488. var BABYLON;
  54489. (function (BABYLON) {
  54490. var GamepadManager = /** @class */ (function () {
  54491. function GamepadManager() {
  54492. var _this = this;
  54493. this._babylonGamepads = [];
  54494. this._oneGamepadConnected = false;
  54495. this._isMonitoring = false;
  54496. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54497. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54498. this._gamepadEventSupported = false;
  54499. }
  54500. else {
  54501. this._gamepadEventSupported = 'GamepadEvent' in window;
  54502. this._gamepadSupport = (navigator.getGamepads ||
  54503. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54504. }
  54505. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54506. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54507. for (var i in _this._babylonGamepads) {
  54508. var gamepad = _this._babylonGamepads[i];
  54509. if (gamepad && gamepad._isConnected) {
  54510. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54511. }
  54512. }
  54513. });
  54514. this._onGamepadConnectedEvent = function (evt) {
  54515. var gamepad = evt.gamepad;
  54516. if (gamepad.index in _this._babylonGamepads) {
  54517. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54518. return;
  54519. }
  54520. }
  54521. var newGamepad;
  54522. if (_this._babylonGamepads[gamepad.index]) {
  54523. newGamepad = _this._babylonGamepads[gamepad.index];
  54524. newGamepad.browserGamepad = gamepad;
  54525. newGamepad._isConnected = true;
  54526. }
  54527. else {
  54528. newGamepad = _this._addNewGamepad(gamepad);
  54529. }
  54530. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54531. _this._startMonitoringGamepads();
  54532. };
  54533. this._onGamepadDisconnectedEvent = function (evt) {
  54534. var gamepad = evt.gamepad;
  54535. // Remove the gamepad from the list of gamepads to monitor.
  54536. for (var i in _this._babylonGamepads) {
  54537. if (_this._babylonGamepads[i].index === gamepad.index) {
  54538. var disconnectedGamepad = _this._babylonGamepads[i];
  54539. disconnectedGamepad._isConnected = false;
  54540. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54541. break;
  54542. }
  54543. }
  54544. };
  54545. if (this._gamepadSupport) {
  54546. //first add already-connected gamepads
  54547. this._updateGamepadObjects();
  54548. if (this._babylonGamepads.length) {
  54549. this._startMonitoringGamepads();
  54550. }
  54551. // Checking if the gamepad connected event is supported (like in Firefox)
  54552. if (this._gamepadEventSupported) {
  54553. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54554. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54555. }
  54556. else {
  54557. this._startMonitoringGamepads();
  54558. }
  54559. }
  54560. }
  54561. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  54562. get: function () {
  54563. return this._babylonGamepads;
  54564. },
  54565. enumerable: true,
  54566. configurable: true
  54567. });
  54568. GamepadManager.prototype.getGamepadByType = function (type) {
  54569. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  54570. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  54571. var gamepad = _a[_i];
  54572. if (gamepad && gamepad.type === type) {
  54573. return gamepad;
  54574. }
  54575. }
  54576. return null;
  54577. };
  54578. GamepadManager.prototype.dispose = function () {
  54579. if (this._gamepadEventSupported) {
  54580. if (this._onGamepadConnectedEvent) {
  54581. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  54582. }
  54583. if (this._onGamepadDisconnectedEvent) {
  54584. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  54585. }
  54586. this._onGamepadConnectedEvent = null;
  54587. this._onGamepadDisconnectedEvent = null;
  54588. }
  54589. this._babylonGamepads.forEach(function (gamepad) {
  54590. gamepad.dispose();
  54591. });
  54592. this.onGamepadConnectedObservable.clear();
  54593. this.onGamepadDisconnectedObservable.clear();
  54594. this._oneGamepadConnected = false;
  54595. this._stopMonitoringGamepads();
  54596. this._babylonGamepads = [];
  54597. };
  54598. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  54599. if (!this._oneGamepadConnected) {
  54600. this._oneGamepadConnected = true;
  54601. }
  54602. var newGamepad;
  54603. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  54604. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54605. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  54606. }
  54607. else if (gamepad.pose) {
  54608. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  54609. }
  54610. else {
  54611. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  54612. }
  54613. this._babylonGamepads[newGamepad.index] = newGamepad;
  54614. return newGamepad;
  54615. };
  54616. GamepadManager.prototype._startMonitoringGamepads = function () {
  54617. if (!this._isMonitoring) {
  54618. this._isMonitoring = true;
  54619. this._checkGamepadsStatus();
  54620. }
  54621. };
  54622. GamepadManager.prototype._stopMonitoringGamepads = function () {
  54623. this._isMonitoring = false;
  54624. };
  54625. GamepadManager.prototype._checkGamepadsStatus = function () {
  54626. var _this = this;
  54627. // Hack to be compatible Chrome
  54628. this._updateGamepadObjects();
  54629. for (var i in this._babylonGamepads) {
  54630. var gamepad = this._babylonGamepads[i];
  54631. if (!gamepad || !gamepad.isConnected) {
  54632. continue;
  54633. }
  54634. gamepad.update();
  54635. }
  54636. if (this._isMonitoring) {
  54637. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  54638. }
  54639. };
  54640. // This function is called only on Chrome, which does not properly support
  54641. // connection/disconnection events and forces you to recopy again the gamepad object
  54642. GamepadManager.prototype._updateGamepadObjects = function () {
  54643. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54644. for (var i = 0; i < gamepads.length; i++) {
  54645. if (gamepads[i]) {
  54646. if (!this._babylonGamepads[gamepads[i].index]) {
  54647. var newGamepad = this._addNewGamepad(gamepads[i]);
  54648. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54649. }
  54650. else {
  54651. // Forced to copy again this object for Chrome for unknown reason
  54652. this._babylonGamepads[i].browserGamepad = gamepads[i];
  54653. if (!this._babylonGamepads[i].isConnected) {
  54654. this._babylonGamepads[i]._isConnected = true;
  54655. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  54656. }
  54657. }
  54658. }
  54659. }
  54660. };
  54661. return GamepadManager;
  54662. }());
  54663. BABYLON.GamepadManager = GamepadManager;
  54664. })(BABYLON || (BABYLON = {}));
  54665. //# sourceMappingURL=babylon.gamepadManager.js.map
  54666. var BABYLON;
  54667. (function (BABYLON) {
  54668. var StickValues = /** @class */ (function () {
  54669. function StickValues(x, y) {
  54670. this.x = x;
  54671. this.y = y;
  54672. }
  54673. return StickValues;
  54674. }());
  54675. BABYLON.StickValues = StickValues;
  54676. var Gamepad = /** @class */ (function () {
  54677. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  54678. if (leftStickX === void 0) { leftStickX = 0; }
  54679. if (leftStickY === void 0) { leftStickY = 1; }
  54680. if (rightStickX === void 0) { rightStickX = 2; }
  54681. if (rightStickY === void 0) { rightStickY = 3; }
  54682. this.id = id;
  54683. this.index = index;
  54684. this.browserGamepad = browserGamepad;
  54685. this._isConnected = true;
  54686. this.type = Gamepad.GAMEPAD;
  54687. this._leftStickAxisX = leftStickX;
  54688. this._leftStickAxisY = leftStickY;
  54689. this._rightStickAxisX = rightStickX;
  54690. this._rightStickAxisY = rightStickY;
  54691. if (this.browserGamepad.axes.length >= 2) {
  54692. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54693. }
  54694. if (this.browserGamepad.axes.length >= 4) {
  54695. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54696. }
  54697. }
  54698. Object.defineProperty(Gamepad.prototype, "isConnected", {
  54699. get: function () {
  54700. return this._isConnected;
  54701. },
  54702. enumerable: true,
  54703. configurable: true
  54704. });
  54705. Gamepad.prototype.onleftstickchanged = function (callback) {
  54706. this._onleftstickchanged = callback;
  54707. };
  54708. Gamepad.prototype.onrightstickchanged = function (callback) {
  54709. this._onrightstickchanged = callback;
  54710. };
  54711. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54712. get: function () {
  54713. return this._leftStick;
  54714. },
  54715. set: function (newValues) {
  54716. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54717. this._onleftstickchanged(newValues);
  54718. }
  54719. this._leftStick = newValues;
  54720. },
  54721. enumerable: true,
  54722. configurable: true
  54723. });
  54724. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54725. get: function () {
  54726. return this._rightStick;
  54727. },
  54728. set: function (newValues) {
  54729. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54730. this._onrightstickchanged(newValues);
  54731. }
  54732. this._rightStick = newValues;
  54733. },
  54734. enumerable: true,
  54735. configurable: true
  54736. });
  54737. Gamepad.prototype.update = function () {
  54738. if (this._leftStick) {
  54739. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54740. }
  54741. if (this._rightStick) {
  54742. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54743. }
  54744. };
  54745. Gamepad.prototype.dispose = function () {
  54746. };
  54747. Gamepad.GAMEPAD = 0;
  54748. Gamepad.GENERIC = 1;
  54749. Gamepad.XBOX = 2;
  54750. Gamepad.POSE_ENABLED = 3;
  54751. return Gamepad;
  54752. }());
  54753. BABYLON.Gamepad = Gamepad;
  54754. var GenericPad = /** @class */ (function (_super) {
  54755. __extends(GenericPad, _super);
  54756. function GenericPad(id, index, browserGamepad) {
  54757. var _this = _super.call(this, id, index, browserGamepad) || this;
  54758. _this.onButtonDownObservable = new BABYLON.Observable();
  54759. _this.onButtonUpObservable = new BABYLON.Observable();
  54760. _this.type = Gamepad.GENERIC;
  54761. _this._buttons = new Array(browserGamepad.buttons.length);
  54762. return _this;
  54763. }
  54764. GenericPad.prototype.onbuttondown = function (callback) {
  54765. this._onbuttondown = callback;
  54766. };
  54767. GenericPad.prototype.onbuttonup = function (callback) {
  54768. this._onbuttonup = callback;
  54769. };
  54770. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54771. if (newValue !== currentValue) {
  54772. if (newValue === 1) {
  54773. if (this._onbuttondown) {
  54774. this._onbuttondown(buttonIndex);
  54775. }
  54776. this.onButtonDownObservable.notifyObservers(buttonIndex);
  54777. }
  54778. if (newValue === 0) {
  54779. if (this._onbuttonup) {
  54780. this._onbuttonup(buttonIndex);
  54781. }
  54782. this.onButtonUpObservable.notifyObservers(buttonIndex);
  54783. }
  54784. }
  54785. return newValue;
  54786. };
  54787. GenericPad.prototype.update = function () {
  54788. _super.prototype.update.call(this);
  54789. for (var index = 0; index < this._buttons.length; index++) {
  54790. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  54791. }
  54792. };
  54793. return GenericPad;
  54794. }(Gamepad));
  54795. BABYLON.GenericPad = GenericPad;
  54796. })(BABYLON || (BABYLON = {}));
  54797. //# sourceMappingURL=babylon.gamepad.js.map
  54798. var BABYLON;
  54799. (function (BABYLON) {
  54800. var Xbox360Button;
  54801. (function (Xbox360Button) {
  54802. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54803. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54804. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54805. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54806. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54807. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54808. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54809. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54810. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54811. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54812. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54813. var Xbox360Dpad;
  54814. (function (Xbox360Dpad) {
  54815. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54816. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54817. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54818. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54819. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54820. var Xbox360Pad = /** @class */ (function (_super) {
  54821. __extends(Xbox360Pad, _super);
  54822. function Xbox360Pad(id, index, gamepad, xboxOne) {
  54823. if (xboxOne === void 0) { xboxOne = false; }
  54824. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  54825. _this._leftTrigger = 0;
  54826. _this._rightTrigger = 0;
  54827. _this.onButtonDownObservable = new BABYLON.Observable();
  54828. _this.onButtonUpObservable = new BABYLON.Observable();
  54829. _this.onPadDownObservable = new BABYLON.Observable();
  54830. _this.onPadUpObservable = new BABYLON.Observable();
  54831. _this._buttonA = 0;
  54832. _this._buttonB = 0;
  54833. _this._buttonX = 0;
  54834. _this._buttonY = 0;
  54835. _this._buttonBack = 0;
  54836. _this._buttonStart = 0;
  54837. _this._buttonLB = 0;
  54838. _this._buttonRB = 0;
  54839. _this._buttonLeftStick = 0;
  54840. _this._buttonRightStick = 0;
  54841. _this._dPadUp = 0;
  54842. _this._dPadDown = 0;
  54843. _this._dPadLeft = 0;
  54844. _this._dPadRight = 0;
  54845. _this._isXboxOnePad = false;
  54846. _this.type = BABYLON.Gamepad.XBOX;
  54847. _this._isXboxOnePad = xboxOne;
  54848. return _this;
  54849. }
  54850. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  54851. this._onlefttriggerchanged = callback;
  54852. };
  54853. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  54854. this._onrighttriggerchanged = callback;
  54855. };
  54856. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  54857. get: function () {
  54858. return this._leftTrigger;
  54859. },
  54860. set: function (newValue) {
  54861. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  54862. this._onlefttriggerchanged(newValue);
  54863. }
  54864. this._leftTrigger = newValue;
  54865. },
  54866. enumerable: true,
  54867. configurable: true
  54868. });
  54869. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  54870. get: function () {
  54871. return this._rightTrigger;
  54872. },
  54873. set: function (newValue) {
  54874. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  54875. this._onrighttriggerchanged(newValue);
  54876. }
  54877. this._rightTrigger = newValue;
  54878. },
  54879. enumerable: true,
  54880. configurable: true
  54881. });
  54882. Xbox360Pad.prototype.onbuttondown = function (callback) {
  54883. this._onbuttondown = callback;
  54884. };
  54885. Xbox360Pad.prototype.onbuttonup = function (callback) {
  54886. this._onbuttonup = callback;
  54887. };
  54888. Xbox360Pad.prototype.ondpaddown = function (callback) {
  54889. this._ondpaddown = callback;
  54890. };
  54891. Xbox360Pad.prototype.ondpadup = function (callback) {
  54892. this._ondpadup = callback;
  54893. };
  54894. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  54895. if (newValue !== currentValue) {
  54896. if (newValue === 1) {
  54897. if (this._onbuttondown) {
  54898. this._onbuttondown(buttonType);
  54899. }
  54900. this.onButtonDownObservable.notifyObservers(buttonType);
  54901. }
  54902. if (newValue === 0) {
  54903. if (this._onbuttonup) {
  54904. this._onbuttonup(buttonType);
  54905. }
  54906. this.onButtonUpObservable.notifyObservers(buttonType);
  54907. }
  54908. }
  54909. return newValue;
  54910. };
  54911. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  54912. if (newValue !== currentValue) {
  54913. if (newValue === 1) {
  54914. if (this._ondpaddown) {
  54915. this._ondpaddown(buttonType);
  54916. }
  54917. this.onPadDownObservable.notifyObservers(buttonType);
  54918. }
  54919. if (newValue === 0) {
  54920. if (this._ondpadup) {
  54921. this._ondpadup(buttonType);
  54922. }
  54923. this.onPadUpObservable.notifyObservers(buttonType);
  54924. }
  54925. }
  54926. return newValue;
  54927. };
  54928. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  54929. get: function () {
  54930. return this._buttonA;
  54931. },
  54932. set: function (value) {
  54933. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  54934. },
  54935. enumerable: true,
  54936. configurable: true
  54937. });
  54938. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  54939. get: function () {
  54940. return this._buttonB;
  54941. },
  54942. set: function (value) {
  54943. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  54944. },
  54945. enumerable: true,
  54946. configurable: true
  54947. });
  54948. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  54949. get: function () {
  54950. return this._buttonX;
  54951. },
  54952. set: function (value) {
  54953. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  54954. },
  54955. enumerable: true,
  54956. configurable: true
  54957. });
  54958. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  54959. get: function () {
  54960. return this._buttonY;
  54961. },
  54962. set: function (value) {
  54963. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  54964. },
  54965. enumerable: true,
  54966. configurable: true
  54967. });
  54968. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  54969. get: function () {
  54970. return this._buttonStart;
  54971. },
  54972. set: function (value) {
  54973. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  54974. },
  54975. enumerable: true,
  54976. configurable: true
  54977. });
  54978. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  54979. get: function () {
  54980. return this._buttonBack;
  54981. },
  54982. set: function (value) {
  54983. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  54984. },
  54985. enumerable: true,
  54986. configurable: true
  54987. });
  54988. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  54989. get: function () {
  54990. return this._buttonLB;
  54991. },
  54992. set: function (value) {
  54993. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  54994. },
  54995. enumerable: true,
  54996. configurable: true
  54997. });
  54998. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  54999. get: function () {
  55000. return this._buttonRB;
  55001. },
  55002. set: function (value) {
  55003. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55004. },
  55005. enumerable: true,
  55006. configurable: true
  55007. });
  55008. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55009. get: function () {
  55010. return this._buttonLeftStick;
  55011. },
  55012. set: function (value) {
  55013. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55014. },
  55015. enumerable: true,
  55016. configurable: true
  55017. });
  55018. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55019. get: function () {
  55020. return this._buttonRightStick;
  55021. },
  55022. set: function (value) {
  55023. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55024. },
  55025. enumerable: true,
  55026. configurable: true
  55027. });
  55028. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55029. get: function () {
  55030. return this._dPadUp;
  55031. },
  55032. set: function (value) {
  55033. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55034. },
  55035. enumerable: true,
  55036. configurable: true
  55037. });
  55038. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55039. get: function () {
  55040. return this._dPadDown;
  55041. },
  55042. set: function (value) {
  55043. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55044. },
  55045. enumerable: true,
  55046. configurable: true
  55047. });
  55048. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55049. get: function () {
  55050. return this._dPadLeft;
  55051. },
  55052. set: function (value) {
  55053. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55054. },
  55055. enumerable: true,
  55056. configurable: true
  55057. });
  55058. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55059. get: function () {
  55060. return this._dPadRight;
  55061. },
  55062. set: function (value) {
  55063. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55064. },
  55065. enumerable: true,
  55066. configurable: true
  55067. });
  55068. Xbox360Pad.prototype.update = function () {
  55069. _super.prototype.update.call(this);
  55070. if (this._isXboxOnePad) {
  55071. this.buttonA = this.browserGamepad.buttons[0].value;
  55072. this.buttonB = this.browserGamepad.buttons[1].value;
  55073. this.buttonX = this.browserGamepad.buttons[2].value;
  55074. this.buttonY = this.browserGamepad.buttons[3].value;
  55075. this.buttonLB = this.browserGamepad.buttons[4].value;
  55076. this.buttonRB = this.browserGamepad.buttons[5].value;
  55077. this.leftTrigger = this.browserGamepad.axes[2];
  55078. this.rightTrigger = this.browserGamepad.axes[5];
  55079. this.buttonBack = this.browserGamepad.buttons[9].value;
  55080. this.buttonStart = this.browserGamepad.buttons[8].value;
  55081. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55082. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55083. this.dPadUp = this.browserGamepad.buttons[11].value;
  55084. this.dPadDown = this.browserGamepad.buttons[12].value;
  55085. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55086. this.dPadRight = this.browserGamepad.buttons[14].value;
  55087. }
  55088. else {
  55089. this.buttonA = this.browserGamepad.buttons[0].value;
  55090. this.buttonB = this.browserGamepad.buttons[1].value;
  55091. this.buttonX = this.browserGamepad.buttons[2].value;
  55092. this.buttonY = this.browserGamepad.buttons[3].value;
  55093. this.buttonLB = this.browserGamepad.buttons[4].value;
  55094. this.buttonRB = this.browserGamepad.buttons[5].value;
  55095. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55096. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55097. this.buttonBack = this.browserGamepad.buttons[8].value;
  55098. this.buttonStart = this.browserGamepad.buttons[9].value;
  55099. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55100. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55101. this.dPadUp = this.browserGamepad.buttons[12].value;
  55102. this.dPadDown = this.browserGamepad.buttons[13].value;
  55103. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55104. this.dPadRight = this.browserGamepad.buttons[15].value;
  55105. }
  55106. };
  55107. return Xbox360Pad;
  55108. }(BABYLON.Gamepad));
  55109. BABYLON.Xbox360Pad = Xbox360Pad;
  55110. })(BABYLON || (BABYLON = {}));
  55111. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55112. var BABYLON;
  55113. (function (BABYLON) {
  55114. var PoseEnabledControllerType;
  55115. (function (PoseEnabledControllerType) {
  55116. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55117. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55118. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55119. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55120. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55121. var PoseEnabledControllerHelper = /** @class */ (function () {
  55122. function PoseEnabledControllerHelper() {
  55123. }
  55124. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55125. // Oculus Touch
  55126. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55127. return new BABYLON.OculusTouchController(vrGamepad);
  55128. }
  55129. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55130. return new BABYLON.WindowsMotionController(vrGamepad);
  55131. }
  55132. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55133. return new BABYLON.ViveController(vrGamepad);
  55134. }
  55135. else {
  55136. return new BABYLON.GenericController(vrGamepad);
  55137. }
  55138. };
  55139. return PoseEnabledControllerHelper;
  55140. }());
  55141. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55142. var PoseEnabledController = /** @class */ (function (_super) {
  55143. __extends(PoseEnabledController, _super);
  55144. function PoseEnabledController(browserGamepad) {
  55145. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55146. _this.deviceScaleFactor = 1;
  55147. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55148. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55149. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55150. _this.position = BABYLON.Vector3.Zero();
  55151. _this.rotationQuaternion = new BABYLON.Quaternion();
  55152. _this.devicePosition = BABYLON.Vector3.Zero();
  55153. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55154. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55155. _this._calculatedRotation = new BABYLON.Quaternion();
  55156. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55157. return _this;
  55158. }
  55159. PoseEnabledController.prototype.update = function () {
  55160. _super.prototype.update.call(this);
  55161. var pose = this.browserGamepad.pose;
  55162. this.updateFromDevice(pose);
  55163. if (this._mesh) {
  55164. this._mesh.position.copyFrom(this._calculatedPosition);
  55165. if (this._mesh.rotationQuaternion) {
  55166. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55167. }
  55168. }
  55169. };
  55170. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55171. if (poseData) {
  55172. this.rawPose = poseData;
  55173. if (poseData.position) {
  55174. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55175. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55176. this.devicePosition.z *= -1;
  55177. }
  55178. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55179. this._calculatedPosition.addInPlace(this.position);
  55180. }
  55181. var pose = this.rawPose;
  55182. if (poseData.orientation && pose.orientation) {
  55183. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55184. if (this._mesh) {
  55185. if (this._mesh.getScene().useRightHandedSystem) {
  55186. this.deviceRotationQuaternion.z *= -1;
  55187. this.deviceRotationQuaternion.w *= -1;
  55188. }
  55189. else {
  55190. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55191. }
  55192. }
  55193. // if the camera is set, rotate to the camera's rotation
  55194. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55195. }
  55196. }
  55197. };
  55198. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55199. if (this._mesh) {
  55200. this._mesh.parent = null;
  55201. }
  55202. this._mesh = mesh;
  55203. if (this._poseControlledCamera) {
  55204. this._mesh.parent = this._poseControlledCamera;
  55205. }
  55206. if (!this._mesh.rotationQuaternion) {
  55207. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55208. }
  55209. };
  55210. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55211. this._poseControlledCamera = camera;
  55212. if (this._mesh) {
  55213. this._mesh.parent = this._poseControlledCamera;
  55214. }
  55215. };
  55216. PoseEnabledController.prototype.dispose = function () {
  55217. if (this._mesh) {
  55218. this._mesh.dispose();
  55219. }
  55220. this._mesh = null;
  55221. _super.prototype.dispose.call(this);
  55222. };
  55223. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55224. get: function () {
  55225. return this._mesh;
  55226. },
  55227. enumerable: true,
  55228. configurable: true
  55229. });
  55230. PoseEnabledController.prototype.getForwardRay = function (length) {
  55231. if (length === void 0) { length = 100; }
  55232. if (!this.mesh) {
  55233. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55234. }
  55235. var m = this.mesh.getWorldMatrix();
  55236. var origin = m.getTranslation();
  55237. var forward = new BABYLON.Vector3(0, 0, -1);
  55238. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55239. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55240. return new BABYLON.Ray(origin, direction, length);
  55241. };
  55242. return PoseEnabledController;
  55243. }(BABYLON.Gamepad));
  55244. BABYLON.PoseEnabledController = PoseEnabledController;
  55245. })(BABYLON || (BABYLON = {}));
  55246. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55247. var BABYLON;
  55248. (function (BABYLON) {
  55249. var WebVRController = /** @class */ (function (_super) {
  55250. __extends(WebVRController, _super);
  55251. function WebVRController(vrGamepad) {
  55252. var _this = _super.call(this, vrGamepad) || this;
  55253. // Observables
  55254. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55255. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55256. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55257. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55258. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55259. _this.pad = { x: 0, y: 0 };
  55260. // avoid GC, store state in a tmp object
  55261. _this._changes = {
  55262. pressChanged: false,
  55263. touchChanged: false,
  55264. valueChanged: false,
  55265. changed: false
  55266. };
  55267. _this._buttons = new Array(vrGamepad.buttons.length);
  55268. _this.hand = vrGamepad.hand;
  55269. return _this;
  55270. }
  55271. WebVRController.prototype.onButtonStateChange = function (callback) {
  55272. this._onButtonStateChange = callback;
  55273. };
  55274. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55275. get: function () {
  55276. return this._defaultModel;
  55277. },
  55278. enumerable: true,
  55279. configurable: true
  55280. });
  55281. WebVRController.prototype.update = function () {
  55282. _super.prototype.update.call(this);
  55283. for (var index = 0; index < this._buttons.length; index++) {
  55284. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55285. }
  55286. ;
  55287. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55288. this.pad.x = this.leftStick.x;
  55289. this.pad.y = this.leftStick.y;
  55290. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55291. }
  55292. };
  55293. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55294. if (!newState) {
  55295. newState = {
  55296. pressed: false,
  55297. touched: false,
  55298. value: 0
  55299. };
  55300. }
  55301. if (!currentState) {
  55302. this._buttons[buttonIndex] = {
  55303. pressed: newState.pressed,
  55304. touched: newState.touched,
  55305. value: newState.value
  55306. };
  55307. return;
  55308. }
  55309. this._checkChanges(newState, currentState);
  55310. if (this._changes.changed) {
  55311. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55312. this.handleButtonChange(buttonIndex, newState, this._changes);
  55313. }
  55314. this._buttons[buttonIndex].pressed = newState.pressed;
  55315. this._buttons[buttonIndex].touched = newState.touched;
  55316. // oculus triggers are never 0, thou not touched.
  55317. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55318. };
  55319. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55320. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55321. this._changes.touchChanged = newState.touched !== currentState.touched;
  55322. this._changes.valueChanged = newState.value !== currentState.value;
  55323. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55324. return this._changes;
  55325. };
  55326. WebVRController.prototype.dispose = function () {
  55327. _super.prototype.dispose.call(this);
  55328. this.onTriggerStateChangedObservable.clear();
  55329. this.onMainButtonStateChangedObservable.clear();
  55330. this.onSecondaryButtonStateChangedObservable.clear();
  55331. this.onPadStateChangedObservable.clear();
  55332. this.onPadValuesChangedObservable.clear();
  55333. };
  55334. return WebVRController;
  55335. }(BABYLON.PoseEnabledController));
  55336. BABYLON.WebVRController = WebVRController;
  55337. })(BABYLON || (BABYLON = {}));
  55338. //# sourceMappingURL=babylon.webVRController.js.map
  55339. var BABYLON;
  55340. (function (BABYLON) {
  55341. var OculusTouchController = /** @class */ (function (_super) {
  55342. __extends(OculusTouchController, _super);
  55343. function OculusTouchController(vrGamepad) {
  55344. var _this = _super.call(this, vrGamepad) || this;
  55345. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55346. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55347. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55348. return _this;
  55349. }
  55350. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55351. var _this = this;
  55352. var meshName;
  55353. // Hand
  55354. if (this.hand === 'left') {
  55355. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55356. }
  55357. else {
  55358. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55359. }
  55360. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55361. /*
  55362. Parent Mesh name: oculus_touch_left
  55363. - body
  55364. - trigger
  55365. - thumbstick
  55366. - grip
  55367. - button_y
  55368. - button_x
  55369. - button_enter
  55370. */
  55371. _this._defaultModel = newMeshes[1];
  55372. _this.attachToMesh(_this._defaultModel);
  55373. if (meshLoaded) {
  55374. meshLoaded(_this._defaultModel);
  55375. }
  55376. });
  55377. };
  55378. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55379. // helper getters for left and right hand.
  55380. get: function () {
  55381. if (this.hand === 'right') {
  55382. return this.onMainButtonStateChangedObservable;
  55383. }
  55384. else {
  55385. throw new Error('No A button on left hand');
  55386. }
  55387. },
  55388. enumerable: true,
  55389. configurable: true
  55390. });
  55391. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55392. get: function () {
  55393. if (this.hand === 'right') {
  55394. return this.onSecondaryButtonStateChangedObservable;
  55395. }
  55396. else {
  55397. throw new Error('No B button on left hand');
  55398. }
  55399. },
  55400. enumerable: true,
  55401. configurable: true
  55402. });
  55403. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55404. get: function () {
  55405. if (this.hand === 'left') {
  55406. return this.onMainButtonStateChangedObservable;
  55407. }
  55408. else {
  55409. throw new Error('No X button on right hand');
  55410. }
  55411. },
  55412. enumerable: true,
  55413. configurable: true
  55414. });
  55415. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55416. get: function () {
  55417. if (this.hand === 'left') {
  55418. return this.onSecondaryButtonStateChangedObservable;
  55419. }
  55420. else {
  55421. throw new Error('No Y button on right hand');
  55422. }
  55423. },
  55424. enumerable: true,
  55425. configurable: true
  55426. });
  55427. /*
  55428. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55429. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55430. 2) secondary trigger (same)
  55431. 3) A (right) X (left), touch, pressed = value
  55432. 4) B / Y
  55433. 5) thumb rest
  55434. */
  55435. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55436. var notifyObject = state; //{ state: state, changes: changes };
  55437. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55438. switch (buttonIdx) {
  55439. case 0:
  55440. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55441. return;
  55442. case 1:// index trigger
  55443. if (this._defaultModel) {
  55444. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55445. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55446. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55447. }
  55448. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55449. return;
  55450. case 2:// secondary trigger
  55451. if (this._defaultModel) {
  55452. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55453. }
  55454. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55455. return;
  55456. case 3:
  55457. if (this._defaultModel) {
  55458. if (notifyObject.pressed) {
  55459. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55460. }
  55461. else {
  55462. (this._defaultModel.getChildren()[1]).position.y = 0;
  55463. }
  55464. }
  55465. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55466. return;
  55467. case 4:
  55468. if (this._defaultModel) {
  55469. if (notifyObject.pressed) {
  55470. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55471. }
  55472. else {
  55473. (this._defaultModel.getChildren()[2]).position.y = 0;
  55474. }
  55475. }
  55476. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55477. return;
  55478. case 5:
  55479. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55480. return;
  55481. }
  55482. };
  55483. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55484. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55485. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55486. return OculusTouchController;
  55487. }(BABYLON.WebVRController));
  55488. BABYLON.OculusTouchController = OculusTouchController;
  55489. })(BABYLON || (BABYLON = {}));
  55490. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55491. var BABYLON;
  55492. (function (BABYLON) {
  55493. var ViveController = /** @class */ (function (_super) {
  55494. __extends(ViveController, _super);
  55495. function ViveController(vrGamepad) {
  55496. var _this = _super.call(this, vrGamepad) || this;
  55497. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55498. return _this;
  55499. }
  55500. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55501. var _this = this;
  55502. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55503. /*
  55504. Parent Mesh name: ViveWand
  55505. - body
  55506. - r_gripper
  55507. - l_gripper
  55508. - menu_button
  55509. - system_button
  55510. - trackpad
  55511. - trigger
  55512. - LED
  55513. */
  55514. _this._defaultModel = newMeshes[1];
  55515. _this.attachToMesh(_this._defaultModel);
  55516. if (meshLoaded) {
  55517. meshLoaded(_this._defaultModel);
  55518. }
  55519. });
  55520. };
  55521. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55522. get: function () {
  55523. return this.onMainButtonStateChangedObservable;
  55524. },
  55525. enumerable: true,
  55526. configurable: true
  55527. });
  55528. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55529. get: function () {
  55530. return this.onMainButtonStateChangedObservable;
  55531. },
  55532. enumerable: true,
  55533. configurable: true
  55534. });
  55535. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55536. get: function () {
  55537. return this.onSecondaryButtonStateChangedObservable;
  55538. },
  55539. enumerable: true,
  55540. configurable: true
  55541. });
  55542. /**
  55543. * Vive mapping:
  55544. * 0: touchpad
  55545. * 1: trigger
  55546. * 2: left AND right buttons
  55547. * 3: menu button
  55548. */
  55549. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55550. var notifyObject = state; //{ state: state, changes: changes };
  55551. switch (buttonIdx) {
  55552. case 0:
  55553. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55554. return;
  55555. case 1:// index trigger
  55556. if (this._defaultModel) {
  55557. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55558. }
  55559. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55560. return;
  55561. case 2:// left AND right button
  55562. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55563. return;
  55564. case 3:
  55565. if (this._defaultModel) {
  55566. if (notifyObject.pressed) {
  55567. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55568. }
  55569. else {
  55570. (this._defaultModel.getChildren()[2]).position.y = 0;
  55571. }
  55572. }
  55573. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55574. return;
  55575. }
  55576. };
  55577. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  55578. ViveController.MODEL_FILENAME = 'wand.babylon';
  55579. return ViveController;
  55580. }(BABYLON.WebVRController));
  55581. BABYLON.ViveController = ViveController;
  55582. })(BABYLON || (BABYLON = {}));
  55583. //# sourceMappingURL=babylon.viveController.js.map
  55584. var BABYLON;
  55585. (function (BABYLON) {
  55586. var GenericController = /** @class */ (function (_super) {
  55587. __extends(GenericController, _super);
  55588. function GenericController(vrGamepad) {
  55589. return _super.call(this, vrGamepad) || this;
  55590. }
  55591. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55592. var _this = this;
  55593. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  55594. _this._defaultModel = newMeshes[1];
  55595. _this.attachToMesh(_this._defaultModel);
  55596. if (meshLoaded) {
  55597. meshLoaded(_this._defaultModel);
  55598. }
  55599. });
  55600. };
  55601. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55602. console.log("Button id: " + buttonIdx + "state: ");
  55603. console.dir(state);
  55604. };
  55605. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  55606. GenericController.MODEL_FILENAME = 'generic.babylon';
  55607. return GenericController;
  55608. }(BABYLON.WebVRController));
  55609. BABYLON.GenericController = GenericController;
  55610. })(BABYLON || (BABYLON = {}));
  55611. //# sourceMappingURL=babylon.genericController.js.map
  55612. var BABYLON;
  55613. (function (BABYLON) {
  55614. var LoadedMeshInfo = /** @class */ (function () {
  55615. function LoadedMeshInfo() {
  55616. this.buttonMeshes = {};
  55617. this.axisMeshes = {};
  55618. }
  55619. return LoadedMeshInfo;
  55620. }());
  55621. var WindowsMotionController = /** @class */ (function (_super) {
  55622. __extends(WindowsMotionController, _super);
  55623. function WindowsMotionController(vrGamepad) {
  55624. var _this = _super.call(this, vrGamepad) || this;
  55625. _this._mapping = {
  55626. // Semantic button names
  55627. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  55628. // A mapping of the button name to glTF model node name
  55629. // that should be transformed by button value.
  55630. buttonMeshNames: {
  55631. 'trigger': 'SELECT',
  55632. 'menu': 'MENU',
  55633. 'grip': 'GRASP',
  55634. 'thumbstick': 'THUMBSTICK_PRESS',
  55635. 'trackpad': 'TOUCHPAD_PRESS'
  55636. },
  55637. // This mapping is used to translate from the Motion Controller to Babylon semantics
  55638. buttonObservableNames: {
  55639. 'trigger': 'onTriggerStateChangedObservable',
  55640. 'menu': 'onSecondaryButtonStateChangedObservable',
  55641. 'grip': 'onMainButtonStateChangedObservable',
  55642. 'thumbstick': 'onPadStateChangedObservable',
  55643. 'trackpad': 'onTrackpadChangedObservable'
  55644. },
  55645. // A mapping of the axis name to glTF model node name
  55646. // that should be transformed by axis value.
  55647. // This array mirrors the browserGamepad.axes array, such that
  55648. // the mesh corresponding to axis 0 is in this array index 0.
  55649. axisMeshNames: [
  55650. 'THUMBSTICK_X',
  55651. 'THUMBSTICK_Y',
  55652. 'TOUCHPAD_TOUCH_X',
  55653. 'TOUCHPAD_TOUCH_Y'
  55654. ],
  55655. pointingPoseMeshName: 'POINTING_POSE'
  55656. };
  55657. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  55658. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  55659. _this._loadedMeshInfo = null;
  55660. return _this;
  55661. }
  55662. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  55663. get: function () {
  55664. return this.onTriggerStateChangedObservable;
  55665. },
  55666. enumerable: true,
  55667. configurable: true
  55668. });
  55669. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  55670. get: function () {
  55671. return this.onSecondaryButtonStateChangedObservable;
  55672. },
  55673. enumerable: true,
  55674. configurable: true
  55675. });
  55676. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  55677. get: function () {
  55678. return this.onMainButtonStateChangedObservable;
  55679. },
  55680. enumerable: true,
  55681. configurable: true
  55682. });
  55683. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  55684. get: function () {
  55685. return this.onPadStateChangedObservable;
  55686. },
  55687. enumerable: true,
  55688. configurable: true
  55689. });
  55690. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  55691. get: function () {
  55692. return this.onTrackpadChangedObservable;
  55693. },
  55694. enumerable: true,
  55695. configurable: true
  55696. });
  55697. /**
  55698. * Called once per frame by the engine.
  55699. */
  55700. WindowsMotionController.prototype.update = function () {
  55701. _super.prototype.update.call(this);
  55702. // Only need to animate axes if there is a loaded mesh
  55703. if (this._loadedMeshInfo) {
  55704. if (this.browserGamepad.axes) {
  55705. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  55706. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  55707. }
  55708. }
  55709. }
  55710. };
  55711. /**
  55712. * Called once for each button that changed state since the last frame
  55713. * @param buttonIdx Which button index changed
  55714. * @param state New state of the button
  55715. * @param changes Which properties on the state changed since last frame
  55716. */
  55717. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55718. var buttonName = this._mapping.buttons[buttonIdx];
  55719. if (!buttonName) {
  55720. return;
  55721. }
  55722. // Only emit events for buttons that we know how to map from index to name
  55723. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  55724. if (observable) {
  55725. observable.notifyObservers(state);
  55726. }
  55727. this.lerpButtonTransform(buttonName, state.value);
  55728. };
  55729. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  55730. // If there is no loaded mesh, there is nothing to transform.
  55731. if (!this._loadedMeshInfo) {
  55732. return;
  55733. }
  55734. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  55735. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55736. return;
  55737. }
  55738. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  55739. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  55740. };
  55741. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  55742. if (!this._loadedMeshInfo) {
  55743. return;
  55744. }
  55745. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  55746. if (!meshInfo) {
  55747. return;
  55748. }
  55749. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55750. return;
  55751. }
  55752. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  55753. var lerpValue = axisValue * 0.5 + 0.5;
  55754. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  55755. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  55756. };
  55757. /**
  55758. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  55759. * @param scene scene in which to add meshes
  55760. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  55761. */
  55762. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  55763. var _this = this;
  55764. if (forceDefault === void 0) { forceDefault = false; }
  55765. var path;
  55766. var filename;
  55767. // Checking if GLB loader is present
  55768. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  55769. // Determine the device specific folder based on the ID suffix
  55770. var device = 'default';
  55771. if (this.id && !forceDefault) {
  55772. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  55773. device = ((match && match[0]) || device);
  55774. }
  55775. // Hand
  55776. if (this.hand === 'left') {
  55777. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  55778. }
  55779. else {
  55780. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  55781. }
  55782. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  55783. }
  55784. else {
  55785. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  55786. path = BABYLON.GenericController.MODEL_BASE_URL;
  55787. filename = BABYLON.GenericController.MODEL_FILENAME;
  55788. }
  55789. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  55790. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  55791. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  55792. if (!_this._loadedMeshInfo) {
  55793. return;
  55794. }
  55795. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  55796. _this.attachToMesh(_this._defaultModel);
  55797. if (meshLoaded) {
  55798. meshLoaded(_this._defaultModel);
  55799. }
  55800. }, null, function (scene, message) {
  55801. BABYLON.Tools.Log(message);
  55802. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  55803. if (!forceDefault) {
  55804. _this.initControllerMesh(scene, meshLoaded, true);
  55805. }
  55806. });
  55807. };
  55808. /**
  55809. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  55810. * can be transformed by button presses and axes values, based on this._mapping.
  55811. *
  55812. * @param scene scene in which the meshes exist
  55813. * @param meshes list of meshes that make up the controller model to process
  55814. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  55815. */
  55816. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  55817. var loadedMeshInfo = null;
  55818. // Create a new mesh to contain the glTF hierarchy
  55819. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  55820. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  55821. var childMesh = null;
  55822. for (var i = 0; i < meshes.length; i++) {
  55823. var mesh = meshes[i];
  55824. if (!mesh.parent) {
  55825. // Exclude controller meshes from picking results
  55826. mesh.isPickable = false;
  55827. // Handle root node, attach to the new parentMesh
  55828. childMesh = mesh;
  55829. break;
  55830. }
  55831. }
  55832. if (childMesh) {
  55833. childMesh.setParent(parentMesh);
  55834. // Create our mesh info. Note that this method will always return non-null.
  55835. loadedMeshInfo = this.createMeshInfo(parentMesh);
  55836. }
  55837. else {
  55838. BABYLON.Tools.Warn('Could not find root node in model file.');
  55839. }
  55840. return loadedMeshInfo;
  55841. };
  55842. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  55843. var loadedMeshInfo = new LoadedMeshInfo();
  55844. var i;
  55845. loadedMeshInfo.rootNode = rootNode;
  55846. // Reset the caches
  55847. loadedMeshInfo.buttonMeshes = {};
  55848. loadedMeshInfo.axisMeshes = {};
  55849. // Button Meshes
  55850. for (i = 0; i < this._mapping.buttons.length; i++) {
  55851. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  55852. if (!buttonMeshName) {
  55853. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  55854. continue;
  55855. }
  55856. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  55857. if (!buttonMesh) {
  55858. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  55859. continue;
  55860. }
  55861. var buttonMeshInfo = {
  55862. index: i,
  55863. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  55864. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  55865. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  55866. };
  55867. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  55868. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  55869. }
  55870. else {
  55871. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  55872. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  55873. '(VALUE: ' + !!buttonMeshInfo.value +
  55874. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  55875. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  55876. ')');
  55877. }
  55878. }
  55879. // Axis Meshes
  55880. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  55881. var axisMeshName = this._mapping.axisMeshNames[i];
  55882. if (!axisMeshName) {
  55883. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  55884. continue;
  55885. }
  55886. var axisMesh = getChildByName(rootNode, axisMeshName);
  55887. if (!axisMesh) {
  55888. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  55889. continue;
  55890. }
  55891. var axisMeshInfo = {
  55892. index: i,
  55893. value: getImmediateChildByName(axisMesh, 'VALUE'),
  55894. min: getImmediateChildByName(axisMesh, 'MIN'),
  55895. max: getImmediateChildByName(axisMesh, 'MAX')
  55896. };
  55897. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  55898. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  55899. }
  55900. else {
  55901. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  55902. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  55903. '(VALUE: ' + !!axisMeshInfo.value +
  55904. ', MIN: ' + !!axisMeshInfo.min +
  55905. ', MAX:' + !!axisMeshInfo.max +
  55906. ')');
  55907. }
  55908. }
  55909. // Pointing Ray
  55910. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  55911. if (!loadedMeshInfo.pointingPoseNode) {
  55912. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  55913. }
  55914. return loadedMeshInfo;
  55915. // Look through all children recursively. This will return null if no mesh exists with the given name.
  55916. function getChildByName(node, name) {
  55917. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  55918. }
  55919. // Look through only immediate children. This will return null if no mesh exists with the given name.
  55920. function getImmediateChildByName(node, name) {
  55921. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  55922. }
  55923. };
  55924. WindowsMotionController.prototype.getForwardRay = function (length) {
  55925. if (length === void 0) { length = 100; }
  55926. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  55927. return _super.prototype.getForwardRay.call(this, length);
  55928. }
  55929. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  55930. var origin = m.getTranslation();
  55931. var forward = new BABYLON.Vector3(0, 0, -1);
  55932. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55933. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55934. return new BABYLON.Ray(origin, direction, length);
  55935. };
  55936. WindowsMotionController.prototype.dispose = function () {
  55937. _super.prototype.dispose.call(this);
  55938. this.onTrackpadChangedObservable.clear();
  55939. };
  55940. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  55941. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  55942. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  55943. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  55944. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  55945. return WindowsMotionController;
  55946. }(BABYLON.WebVRController));
  55947. BABYLON.WindowsMotionController = WindowsMotionController;
  55948. })(BABYLON || (BABYLON = {}));
  55949. //# sourceMappingURL=babylon.windowsMotionController.js.map
  55950. /// <reference path="babylon.targetCamera.ts" />
  55951. var BABYLON;
  55952. (function (BABYLON) {
  55953. var FollowCamera = /** @class */ (function (_super) {
  55954. __extends(FollowCamera, _super);
  55955. function FollowCamera(name, position, scene, lockedTarget) {
  55956. if (lockedTarget === void 0) { lockedTarget = null; }
  55957. var _this = _super.call(this, name, position, scene) || this;
  55958. _this.radius = 12;
  55959. _this.rotationOffset = 0;
  55960. _this.heightOffset = 4;
  55961. _this.cameraAcceleration = 0.05;
  55962. _this.maxCameraSpeed = 20;
  55963. _this.lockedTarget = lockedTarget;
  55964. return _this;
  55965. }
  55966. FollowCamera.prototype.getRadians = function (degrees) {
  55967. return degrees * Math.PI / 180;
  55968. };
  55969. FollowCamera.prototype.follow = function (cameraTarget) {
  55970. if (!cameraTarget)
  55971. return;
  55972. var yRotation;
  55973. if (cameraTarget.rotationQuaternion) {
  55974. var rotMatrix = new BABYLON.Matrix();
  55975. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  55976. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  55977. }
  55978. else {
  55979. yRotation = cameraTarget.rotation.y;
  55980. }
  55981. var radians = this.getRadians(this.rotationOffset) + yRotation;
  55982. var targetPosition = cameraTarget.getAbsolutePosition();
  55983. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  55984. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  55985. var dx = targetX - this.position.x;
  55986. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  55987. var dz = (targetZ) - this.position.z;
  55988. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  55989. var vy = dy * this.cameraAcceleration;
  55990. var vz = dz * this.cameraAcceleration * 2;
  55991. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  55992. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  55993. }
  55994. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  55995. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  55996. }
  55997. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  55998. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  55999. }
  56000. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56001. this.setTarget(targetPosition);
  56002. };
  56003. FollowCamera.prototype._checkInputs = function () {
  56004. _super.prototype._checkInputs.call(this);
  56005. if (this.lockedTarget) {
  56006. this.follow(this.lockedTarget);
  56007. }
  56008. };
  56009. FollowCamera.prototype.getClassName = function () {
  56010. return "FollowCamera";
  56011. };
  56012. __decorate([
  56013. BABYLON.serialize()
  56014. ], FollowCamera.prototype, "radius", void 0);
  56015. __decorate([
  56016. BABYLON.serialize()
  56017. ], FollowCamera.prototype, "rotationOffset", void 0);
  56018. __decorate([
  56019. BABYLON.serialize()
  56020. ], FollowCamera.prototype, "heightOffset", void 0);
  56021. __decorate([
  56022. BABYLON.serialize()
  56023. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56024. __decorate([
  56025. BABYLON.serialize()
  56026. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56027. __decorate([
  56028. BABYLON.serializeAsMeshReference("lockedTargetId")
  56029. ], FollowCamera.prototype, "lockedTarget", void 0);
  56030. return FollowCamera;
  56031. }(BABYLON.TargetCamera));
  56032. BABYLON.FollowCamera = FollowCamera;
  56033. var ArcFollowCamera = /** @class */ (function (_super) {
  56034. __extends(ArcFollowCamera, _super);
  56035. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56036. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56037. _this.alpha = alpha;
  56038. _this.beta = beta;
  56039. _this.radius = radius;
  56040. _this.target = target;
  56041. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56042. _this.follow();
  56043. return _this;
  56044. }
  56045. ArcFollowCamera.prototype.follow = function () {
  56046. if (!this.target) {
  56047. return;
  56048. }
  56049. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56050. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56051. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56052. var targetPosition = this.target.getAbsolutePosition();
  56053. this.position = targetPosition.add(this._cartesianCoordinates);
  56054. this.setTarget(targetPosition);
  56055. };
  56056. ArcFollowCamera.prototype._checkInputs = function () {
  56057. _super.prototype._checkInputs.call(this);
  56058. this.follow();
  56059. };
  56060. ArcFollowCamera.prototype.getClassName = function () {
  56061. return "ArcFollowCamera";
  56062. };
  56063. return ArcFollowCamera;
  56064. }(BABYLON.TargetCamera));
  56065. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56066. })(BABYLON || (BABYLON = {}));
  56067. //# sourceMappingURL=babylon.followCamera.js.map
  56068. /// <reference path="babylon.touchCamera.ts" />
  56069. var BABYLON;
  56070. (function (BABYLON) {
  56071. // We're mainly based on the logic defined into the FreeCamera code
  56072. var UniversalCamera = /** @class */ (function (_super) {
  56073. __extends(UniversalCamera, _super);
  56074. //-- end properties for backward compatibility for inputs
  56075. function UniversalCamera(name, position, scene) {
  56076. var _this = _super.call(this, name, position, scene) || this;
  56077. _this.inputs.addGamepad();
  56078. return _this;
  56079. }
  56080. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56081. //-- Begin properties for backward compatibility for inputs
  56082. get: function () {
  56083. var gamepad = this.inputs.attached["gamepad"];
  56084. if (gamepad)
  56085. return gamepad.gamepadAngularSensibility;
  56086. return 0;
  56087. },
  56088. set: function (value) {
  56089. var gamepad = this.inputs.attached["gamepad"];
  56090. if (gamepad)
  56091. gamepad.gamepadAngularSensibility = value;
  56092. },
  56093. enumerable: true,
  56094. configurable: true
  56095. });
  56096. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56097. get: function () {
  56098. var gamepad = this.inputs.attached["gamepad"];
  56099. if (gamepad)
  56100. return gamepad.gamepadMoveSensibility;
  56101. return 0;
  56102. },
  56103. set: function (value) {
  56104. var gamepad = this.inputs.attached["gamepad"];
  56105. if (gamepad)
  56106. gamepad.gamepadMoveSensibility = value;
  56107. },
  56108. enumerable: true,
  56109. configurable: true
  56110. });
  56111. UniversalCamera.prototype.getClassName = function () {
  56112. return "UniversalCamera";
  56113. };
  56114. return UniversalCamera;
  56115. }(BABYLON.TouchCamera));
  56116. BABYLON.UniversalCamera = UniversalCamera;
  56117. })(BABYLON || (BABYLON = {}));
  56118. //# sourceMappingURL=babylon.universalCamera.js.map
  56119. /// <reference path="babylon.universalCamera.ts" />
  56120. var BABYLON;
  56121. (function (BABYLON) {
  56122. // We're mainly based on the logic defined into the FreeCamera code
  56123. var GamepadCamera = /** @class */ (function (_super) {
  56124. __extends(GamepadCamera, _super);
  56125. //-- end properties for backward compatibility for inputs
  56126. function GamepadCamera(name, position, scene) {
  56127. return _super.call(this, name, position, scene) || this;
  56128. }
  56129. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56130. //-- Begin properties for backward compatibility for inputs
  56131. get: function () {
  56132. var gamepad = this.inputs.attached["gamepad"];
  56133. if (gamepad)
  56134. return gamepad.gamepadAngularSensibility;
  56135. return 0;
  56136. },
  56137. set: function (value) {
  56138. var gamepad = this.inputs.attached["gamepad"];
  56139. if (gamepad)
  56140. gamepad.gamepadAngularSensibility = value;
  56141. },
  56142. enumerable: true,
  56143. configurable: true
  56144. });
  56145. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56146. get: function () {
  56147. var gamepad = this.inputs.attached["gamepad"];
  56148. if (gamepad)
  56149. return gamepad.gamepadMoveSensibility;
  56150. return 0;
  56151. },
  56152. set: function (value) {
  56153. var gamepad = this.inputs.attached["gamepad"];
  56154. if (gamepad)
  56155. gamepad.gamepadMoveSensibility = value;
  56156. },
  56157. enumerable: true,
  56158. configurable: true
  56159. });
  56160. GamepadCamera.prototype.getClassName = function () {
  56161. return "GamepadCamera";
  56162. };
  56163. return GamepadCamera;
  56164. }(BABYLON.UniversalCamera));
  56165. BABYLON.GamepadCamera = GamepadCamera;
  56166. })(BABYLON || (BABYLON = {}));
  56167. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56168. var BABYLON;
  56169. (function (BABYLON) {
  56170. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56171. function PostProcessRenderPipelineManager() {
  56172. this._renderPipelines = {};
  56173. }
  56174. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56175. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56176. };
  56177. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56178. if (unique === void 0) { unique = false; }
  56179. var renderPipeline = this._renderPipelines[renderPipelineName];
  56180. if (!renderPipeline) {
  56181. return;
  56182. }
  56183. renderPipeline._attachCameras(cameras, unique);
  56184. };
  56185. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56186. var renderPipeline = this._renderPipelines[renderPipelineName];
  56187. if (!renderPipeline) {
  56188. return;
  56189. }
  56190. renderPipeline._detachCameras(cameras);
  56191. };
  56192. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56193. var renderPipeline = this._renderPipelines[renderPipelineName];
  56194. if (!renderPipeline) {
  56195. return;
  56196. }
  56197. renderPipeline._enableEffect(renderEffectName, cameras);
  56198. };
  56199. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56200. var renderPipeline = this._renderPipelines[renderPipelineName];
  56201. if (!renderPipeline) {
  56202. return;
  56203. }
  56204. renderPipeline._disableEffect(renderEffectName, cameras);
  56205. };
  56206. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56207. var renderPipeline = this._renderPipelines[renderPipelineName];
  56208. if (!renderPipeline) {
  56209. return;
  56210. }
  56211. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56212. };
  56213. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56214. var renderPipeline = this._renderPipelines[renderPipelineName];
  56215. if (!renderPipeline) {
  56216. return;
  56217. }
  56218. renderPipeline._disableDisplayOnlyPass(cameras);
  56219. };
  56220. PostProcessRenderPipelineManager.prototype.update = function () {
  56221. for (var renderPipelineName in this._renderPipelines) {
  56222. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56223. var pipeline = this._renderPipelines[renderPipelineName];
  56224. if (!pipeline.isSupported) {
  56225. pipeline.dispose();
  56226. delete this._renderPipelines[renderPipelineName];
  56227. }
  56228. else {
  56229. pipeline._update();
  56230. }
  56231. }
  56232. }
  56233. };
  56234. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56235. for (var renderPipelineName in this._renderPipelines) {
  56236. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56237. var pipeline = this._renderPipelines[renderPipelineName];
  56238. pipeline._rebuild();
  56239. }
  56240. }
  56241. };
  56242. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56243. for (var renderPipelineName in this._renderPipelines) {
  56244. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56245. var pipeline = this._renderPipelines[renderPipelineName];
  56246. pipeline.dispose();
  56247. }
  56248. }
  56249. };
  56250. return PostProcessRenderPipelineManager;
  56251. }());
  56252. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56253. })(BABYLON || (BABYLON = {}));
  56254. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56255. var BABYLON;
  56256. (function (BABYLON) {
  56257. var PostProcessRenderPass = /** @class */ (function () {
  56258. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56259. this._refCount = 0;
  56260. this._name = name;
  56261. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56262. this.setRenderList(renderList);
  56263. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56264. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56265. this._scene = scene;
  56266. this._renderList = renderList;
  56267. }
  56268. // private
  56269. PostProcessRenderPass.prototype._incRefCount = function () {
  56270. if (this._refCount === 0) {
  56271. this._scene.customRenderTargets.push(this._renderTexture);
  56272. }
  56273. return ++this._refCount;
  56274. };
  56275. PostProcessRenderPass.prototype._decRefCount = function () {
  56276. this._refCount--;
  56277. if (this._refCount <= 0) {
  56278. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56279. }
  56280. return this._refCount;
  56281. };
  56282. PostProcessRenderPass.prototype._update = function () {
  56283. this.setRenderList(this._renderList);
  56284. };
  56285. // public
  56286. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56287. this._renderTexture.renderList = renderList;
  56288. };
  56289. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56290. return this._renderTexture;
  56291. };
  56292. return PostProcessRenderPass;
  56293. }());
  56294. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56295. })(BABYLON || (BABYLON = {}));
  56296. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56297. var BABYLON;
  56298. (function (BABYLON) {
  56299. var PostProcessRenderEffect = /** @class */ (function () {
  56300. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56301. this._engine = engine;
  56302. this._name = name;
  56303. this._singleInstance = singleInstance || true;
  56304. this._getPostProcess = getPostProcess;
  56305. this._cameras = {};
  56306. this._indicesForCamera = {};
  56307. this._postProcesses = {};
  56308. this._renderPasses = {};
  56309. this._renderEffectAsPasses = {};
  56310. }
  56311. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56312. get: function () {
  56313. for (var index in this._postProcesses) {
  56314. if (!this._postProcesses[index].isSupported) {
  56315. return false;
  56316. }
  56317. }
  56318. return true;
  56319. },
  56320. enumerable: true,
  56321. configurable: true
  56322. });
  56323. PostProcessRenderEffect.prototype._update = function () {
  56324. for (var renderPassName in this._renderPasses) {
  56325. this._renderPasses[renderPassName]._update();
  56326. }
  56327. };
  56328. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56329. this._renderPasses[renderPass._name] = renderPass;
  56330. this._linkParameters();
  56331. };
  56332. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56333. delete this._renderPasses[renderPass._name];
  56334. this._linkParameters();
  56335. };
  56336. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56337. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56338. this._linkParameters();
  56339. };
  56340. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56341. for (var renderPassName in this._renderPasses) {
  56342. if (renderPassName === passName) {
  56343. return this._renderPasses[passName];
  56344. }
  56345. }
  56346. return null;
  56347. };
  56348. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56349. this._renderPasses = {};
  56350. this._linkParameters();
  56351. };
  56352. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56353. var cameraKey;
  56354. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56355. if (!cams) {
  56356. return;
  56357. }
  56358. for (var i = 0; i < cams.length; i++) {
  56359. var camera = cams[i];
  56360. var cameraName = camera.name;
  56361. if (this._singleInstance) {
  56362. cameraKey = 0;
  56363. }
  56364. else {
  56365. cameraKey = cameraName;
  56366. }
  56367. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56368. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56369. if (!this._indicesForCamera[cameraName]) {
  56370. this._indicesForCamera[cameraName] = [];
  56371. }
  56372. this._indicesForCamera[cameraName].push(index);
  56373. if (!this._cameras[cameraName]) {
  56374. this._cameras[cameraName] = camera;
  56375. }
  56376. for (var passName in this._renderPasses) {
  56377. this._renderPasses[passName]._incRefCount();
  56378. }
  56379. }
  56380. this._linkParameters();
  56381. };
  56382. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56383. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56384. if (!cams) {
  56385. return;
  56386. }
  56387. for (var i = 0; i < cams.length; i++) {
  56388. var camera = cams[i];
  56389. var cameraName = camera.name;
  56390. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56391. if (this._cameras[cameraName]) {
  56392. //this._indicesForCamera.splice(index, 1);
  56393. this._cameras[cameraName] = null;
  56394. }
  56395. for (var passName in this._renderPasses) {
  56396. this._renderPasses[passName]._decRefCount();
  56397. }
  56398. }
  56399. };
  56400. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56401. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56402. if (!cams) {
  56403. return;
  56404. }
  56405. for (var i = 0; i < cams.length; i++) {
  56406. var camera = cams[i];
  56407. var cameraName = camera.name;
  56408. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56409. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56410. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56411. }
  56412. }
  56413. for (var passName in this._renderPasses) {
  56414. this._renderPasses[passName]._incRefCount();
  56415. }
  56416. }
  56417. };
  56418. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56419. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56420. if (!cams) {
  56421. return;
  56422. }
  56423. for (var i = 0; i < cams.length; i++) {
  56424. var camera = cams[i];
  56425. var cameraName = camera.Name;
  56426. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56427. for (var passName in this._renderPasses) {
  56428. this._renderPasses[passName]._decRefCount();
  56429. }
  56430. }
  56431. };
  56432. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56433. if (this._singleInstance) {
  56434. return this._postProcesses[0];
  56435. }
  56436. else {
  56437. if (!camera) {
  56438. return null;
  56439. }
  56440. return this._postProcesses[camera.name];
  56441. }
  56442. };
  56443. PostProcessRenderEffect.prototype._linkParameters = function () {
  56444. var _this = this;
  56445. for (var index in this._postProcesses) {
  56446. if (this.applyParameters) {
  56447. this.applyParameters(this._postProcesses[index]);
  56448. }
  56449. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56450. _this._linkTextures(effect);
  56451. });
  56452. }
  56453. };
  56454. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56455. for (var renderPassName in this._renderPasses) {
  56456. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56457. }
  56458. for (var renderEffectName in this._renderEffectAsPasses) {
  56459. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56460. }
  56461. };
  56462. return PostProcessRenderEffect;
  56463. }());
  56464. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56465. })(BABYLON || (BABYLON = {}));
  56466. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56467. var BABYLON;
  56468. (function (BABYLON) {
  56469. var PostProcessRenderPipeline = /** @class */ (function () {
  56470. function PostProcessRenderPipeline(engine, name) {
  56471. this._engine = engine;
  56472. this._name = name;
  56473. this._renderEffects = {};
  56474. this._renderEffectsForIsolatedPass = new Array();
  56475. this._cameras = [];
  56476. }
  56477. PostProcessRenderPipeline.prototype.getClassName = function () {
  56478. return "PostProcessRenderPipeline";
  56479. };
  56480. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56481. get: function () {
  56482. for (var renderEffectName in this._renderEffects) {
  56483. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56484. if (!this._renderEffects[renderEffectName].isSupported) {
  56485. return false;
  56486. }
  56487. }
  56488. }
  56489. return true;
  56490. },
  56491. enumerable: true,
  56492. configurable: true
  56493. });
  56494. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56495. this._renderEffects[renderEffect._name] = renderEffect;
  56496. };
  56497. // private
  56498. PostProcessRenderPipeline.prototype._rebuild = function () {
  56499. };
  56500. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56501. var renderEffects = this._renderEffects[renderEffectName];
  56502. if (!renderEffects) {
  56503. return;
  56504. }
  56505. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56506. };
  56507. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56508. var renderEffects = this._renderEffects[renderEffectName];
  56509. if (!renderEffects) {
  56510. return;
  56511. }
  56512. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56513. };
  56514. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  56515. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56516. if (!cams) {
  56517. return;
  56518. }
  56519. var indicesToDelete = [];
  56520. var i;
  56521. for (i = 0; i < cams.length; i++) {
  56522. var camera = cams[i];
  56523. var cameraName = camera.name;
  56524. if (this._cameras.indexOf(camera) === -1) {
  56525. this._cameras[cameraName] = camera;
  56526. }
  56527. else if (unique) {
  56528. indicesToDelete.push(i);
  56529. }
  56530. }
  56531. for (i = 0; i < indicesToDelete.length; i++) {
  56532. cameras.splice(indicesToDelete[i], 1);
  56533. }
  56534. for (var renderEffectName in this._renderEffects) {
  56535. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56536. this._renderEffects[renderEffectName]._attachCameras(cams);
  56537. }
  56538. }
  56539. };
  56540. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56541. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56542. if (!cams) {
  56543. return;
  56544. }
  56545. for (var renderEffectName in this._renderEffects) {
  56546. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56547. this._renderEffects[renderEffectName]._detachCameras(cams);
  56548. }
  56549. }
  56550. for (var i = 0; i < cams.length; i++) {
  56551. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  56552. }
  56553. };
  56554. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56555. var _this = this;
  56556. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56557. if (!cams) {
  56558. return;
  56559. }
  56560. var pass = null;
  56561. var renderEffectName;
  56562. for (renderEffectName in this._renderEffects) {
  56563. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56564. pass = this._renderEffects[renderEffectName].getPass(passName);
  56565. if (pass != null) {
  56566. break;
  56567. }
  56568. }
  56569. }
  56570. if (pass === null) {
  56571. return;
  56572. }
  56573. for (renderEffectName in this._renderEffects) {
  56574. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56575. this._renderEffects[renderEffectName]._disable(cams);
  56576. }
  56577. }
  56578. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  56579. for (var i = 0; i < cams.length; i++) {
  56580. var camera = cams[i];
  56581. var cameraName = camera.name;
  56582. 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); });
  56583. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  56584. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  56585. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  56586. }
  56587. };
  56588. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  56589. var _this = this;
  56590. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56591. if (!cams) {
  56592. return;
  56593. }
  56594. for (var i = 0; i < cams.length; i++) {
  56595. var camera = cams[i];
  56596. var cameraName = camera.name;
  56597. 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); });
  56598. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  56599. }
  56600. for (var renderEffectName in this._renderEffects) {
  56601. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56602. this._renderEffects[renderEffectName]._enable(cams);
  56603. }
  56604. }
  56605. };
  56606. PostProcessRenderPipeline.prototype._update = function () {
  56607. for (var renderEffectName in this._renderEffects) {
  56608. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56609. this._renderEffects[renderEffectName]._update();
  56610. }
  56611. }
  56612. for (var i = 0; i < this._cameras.length; i++) {
  56613. var cameraName = this._cameras[i].name;
  56614. if (this._renderEffectsForIsolatedPass[cameraName]) {
  56615. this._renderEffectsForIsolatedPass[cameraName]._update();
  56616. }
  56617. }
  56618. };
  56619. PostProcessRenderPipeline.prototype._reset = function () {
  56620. this._renderEffects = {};
  56621. this._renderEffectsForIsolatedPass = new Array();
  56622. };
  56623. PostProcessRenderPipeline.prototype.dispose = function () {
  56624. // Must be implemented by children
  56625. };
  56626. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  56627. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  56628. __decorate([
  56629. BABYLON.serialize()
  56630. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  56631. return PostProcessRenderPipeline;
  56632. }());
  56633. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  56634. })(BABYLON || (BABYLON = {}));
  56635. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  56636. var BABYLON;
  56637. (function (BABYLON) {
  56638. var DepthRenderer = /** @class */ (function () {
  56639. function DepthRenderer(scene, type) {
  56640. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  56641. var _this = this;
  56642. this._scene = scene;
  56643. var engine = scene.getEngine();
  56644. // Render target
  56645. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  56646. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56647. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56648. this._depthMap.refreshRate = 1;
  56649. this._depthMap.renderParticles = false;
  56650. this._depthMap.renderList = null;
  56651. // set default depth value to 1.0 (far away)
  56652. this._depthMap.onClearObservable.add(function (engine) {
  56653. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56654. });
  56655. // Custom render function
  56656. var renderSubMesh = function (subMesh) {
  56657. var mesh = subMesh.getRenderingMesh();
  56658. var scene = _this._scene;
  56659. var engine = scene.getEngine();
  56660. var material = subMesh.getMaterial();
  56661. if (!material) {
  56662. return;
  56663. }
  56664. // Culling
  56665. engine.setState(material.backFaceCulling);
  56666. // Managing instances
  56667. var batch = mesh._getInstancesRenderList(subMesh._id);
  56668. if (batch.mustReturn) {
  56669. return;
  56670. }
  56671. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56672. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  56673. engine.enableEffect(_this._effect);
  56674. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  56675. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  56676. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  56677. // Alpha test
  56678. if (material && material.needAlphaTesting()) {
  56679. var alphaTexture = material.getAlphaTestTexture();
  56680. if (alphaTexture) {
  56681. _this._effect.setTexture("diffuseSampler", alphaTexture);
  56682. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56683. }
  56684. }
  56685. // Bones
  56686. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  56687. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56688. }
  56689. // Draw
  56690. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56691. }
  56692. };
  56693. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56694. var index;
  56695. if (depthOnlySubMeshes.length) {
  56696. engine.setColorWrite(false);
  56697. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56698. renderSubMesh(depthOnlySubMeshes.data[index]);
  56699. }
  56700. engine.setColorWrite(true);
  56701. }
  56702. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56703. renderSubMesh(opaqueSubMeshes.data[index]);
  56704. }
  56705. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56706. renderSubMesh(alphaTestSubMeshes.data[index]);
  56707. }
  56708. };
  56709. }
  56710. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  56711. var material = subMesh.getMaterial();
  56712. if (material.disableDepthWrite) {
  56713. return false;
  56714. }
  56715. var defines = [];
  56716. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56717. var mesh = subMesh.getMesh();
  56718. // Alpha test
  56719. if (material && material.needAlphaTesting()) {
  56720. defines.push("#define ALPHATEST");
  56721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56722. attribs.push(BABYLON.VertexBuffer.UVKind);
  56723. defines.push("#define UV1");
  56724. }
  56725. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56726. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56727. defines.push("#define UV2");
  56728. }
  56729. }
  56730. // Bones
  56731. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56732. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56733. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56734. if (mesh.numBoneInfluencers > 4) {
  56735. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56736. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56737. }
  56738. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56739. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  56740. }
  56741. else {
  56742. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56743. }
  56744. // Instances
  56745. if (useInstances) {
  56746. defines.push("#define INSTANCES");
  56747. attribs.push("world0");
  56748. attribs.push("world1");
  56749. attribs.push("world2");
  56750. attribs.push("world3");
  56751. }
  56752. // Get correct effect
  56753. var join = defines.join("\n");
  56754. if (this._cachedDefines !== join) {
  56755. this._cachedDefines = join;
  56756. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  56757. }
  56758. return this._effect.isReady();
  56759. };
  56760. DepthRenderer.prototype.getDepthMap = function () {
  56761. return this._depthMap;
  56762. };
  56763. // Methods
  56764. DepthRenderer.prototype.dispose = function () {
  56765. this._depthMap.dispose();
  56766. };
  56767. return DepthRenderer;
  56768. }());
  56769. BABYLON.DepthRenderer = DepthRenderer;
  56770. })(BABYLON || (BABYLON = {}));
  56771. //# sourceMappingURL=babylon.depthRenderer.js.map
  56772. var BABYLON;
  56773. (function (BABYLON) {
  56774. var SSAORenderingPipeline = /** @class */ (function (_super) {
  56775. __extends(SSAORenderingPipeline, _super);
  56776. /**
  56777. * @constructor
  56778. * @param {string} name - The rendering pipeline name
  56779. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56780. * @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 }
  56781. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56782. */
  56783. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  56784. var _this = _super.call(this, scene.getEngine(), name) || this;
  56785. // Members
  56786. /**
  56787. * The PassPostProcess id in the pipeline that contains the original scene color
  56788. * @type {string}
  56789. */
  56790. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  56791. /**
  56792. * The SSAO PostProcess id in the pipeline
  56793. * @type {string}
  56794. */
  56795. _this.SSAORenderEffect = "SSAORenderEffect";
  56796. /**
  56797. * The horizontal blur PostProcess id in the pipeline
  56798. * @type {string}
  56799. */
  56800. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  56801. /**
  56802. * The vertical blur PostProcess id in the pipeline
  56803. * @type {string}
  56804. */
  56805. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  56806. /**
  56807. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  56808. * @type {string}
  56809. */
  56810. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  56811. /**
  56812. * The output strength of the SSAO post-process. Default value is 1.0.
  56813. * @type {number}
  56814. */
  56815. _this.totalStrength = 1.0;
  56816. /**
  56817. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  56818. * @type {number}
  56819. */
  56820. _this.radius = 0.0001;
  56821. /**
  56822. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  56823. * Must not be equal to fallOff and superior to fallOff.
  56824. * Default value is 0.975
  56825. * @type {number}
  56826. */
  56827. _this.area = 0.0075;
  56828. /**
  56829. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  56830. * Must not be equal to area and inferior to area.
  56831. * Default value is 0.0
  56832. * @type {number}
  56833. */
  56834. _this.fallOff = 0.000001;
  56835. /**
  56836. * The base color of the SSAO post-process
  56837. * The final result is "base + ssao" between [0, 1]
  56838. * @type {number}
  56839. */
  56840. _this.base = 0.5;
  56841. _this._firstUpdate = true;
  56842. _this._scene = scene;
  56843. // Set up assets
  56844. _this._createRandomTexture();
  56845. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56846. var ssaoRatio = ratio.ssaoRatio || ratio;
  56847. var combineRatio = ratio.combineRatio || ratio;
  56848. _this._ratio = {
  56849. ssaoRatio: ssaoRatio,
  56850. combineRatio: combineRatio
  56851. };
  56852. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  56853. _this._createSSAOPostProcess(ssaoRatio);
  56854. _this._createBlurPostProcess(ssaoRatio);
  56855. _this._createSSAOCombinePostProcess(combineRatio);
  56856. // Set up pipeline
  56857. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  56858. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  56859. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  56860. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  56861. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  56862. // Finish
  56863. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56864. if (cameras)
  56865. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56866. return _this;
  56867. }
  56868. // Public Methods
  56869. /**
  56870. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  56871. */
  56872. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  56873. if (disableDepthRender === void 0) { disableDepthRender = false; }
  56874. for (var i = 0; i < this._scene.cameras.length; i++) {
  56875. var camera = this._scene.cameras[i];
  56876. this._originalColorPostProcess.dispose(camera);
  56877. this._ssaoPostProcess.dispose(camera);
  56878. this._blurHPostProcess.dispose(camera);
  56879. this._blurVPostProcess.dispose(camera);
  56880. this._ssaoCombinePostProcess.dispose(camera);
  56881. }
  56882. this._randomTexture.dispose();
  56883. if (disableDepthRender)
  56884. this._scene.disableDepthRenderer();
  56885. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56886. _super.prototype.dispose.call(this);
  56887. };
  56888. // Private Methods
  56889. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  56890. var _this = this;
  56891. /*
  56892. var samplerOffsets = [
  56893. -8.0, -6.0, -4.0, -2.0,
  56894. 0.0,
  56895. 2.0, 4.0, 6.0, 8.0
  56896. ];
  56897. */
  56898. var samplerOffsets = new Array();
  56899. for (var i = -8; i < 8; i++) {
  56900. samplerOffsets.push(i * 2);
  56901. }
  56902. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  56903. this._blurHPostProcess.onApply = function (effect) {
  56904. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  56905. effect.setTexture("depthSampler", _this._depthTexture);
  56906. if (_this._firstUpdate) {
  56907. effect.setArray("samplerOffsets", samplerOffsets);
  56908. }
  56909. };
  56910. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  56911. this._blurVPostProcess.onApply = function (effect) {
  56912. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  56913. effect.setTexture("depthSampler", _this._depthTexture);
  56914. if (_this._firstUpdate) {
  56915. effect.setArray("samplerOffsets", samplerOffsets);
  56916. _this._firstUpdate = false;
  56917. }
  56918. };
  56919. };
  56920. SSAORenderingPipeline.prototype._rebuild = function () {
  56921. this._firstUpdate = true;
  56922. _super.prototype._rebuild.call(this);
  56923. };
  56924. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  56925. var _this = this;
  56926. var numSamples = 16;
  56927. var sampleSphere = [
  56928. 0.5381, 0.1856, -0.4319,
  56929. 0.1379, 0.2486, 0.4430,
  56930. 0.3371, 0.5679, -0.0057,
  56931. -0.6999, -0.0451, -0.0019,
  56932. 0.0689, -0.1598, -0.8547,
  56933. 0.0560, 0.0069, -0.1843,
  56934. -0.0146, 0.1402, 0.0762,
  56935. 0.0100, -0.1924, -0.0344,
  56936. -0.3577, -0.5301, -0.4358,
  56937. -0.3169, 0.1063, 0.0158,
  56938. 0.0103, -0.5869, 0.0046,
  56939. -0.0897, -0.4940, 0.3287,
  56940. 0.7119, -0.0154, -0.0918,
  56941. -0.0533, 0.0596, -0.5411,
  56942. 0.0352, -0.0631, 0.5460,
  56943. -0.4776, 0.2847, -0.0271
  56944. ];
  56945. var samplesFactor = 1.0 / numSamples;
  56946. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  56947. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  56948. "area", "fallOff", "base", "range", "viewport"
  56949. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  56950. this._ssaoPostProcess.onApply = function (effect) {
  56951. if (_this._firstUpdate) {
  56952. effect.setArray3("sampleSphere", sampleSphere);
  56953. effect.setFloat("samplesFactor", samplesFactor);
  56954. effect.setFloat("randTextureTiles", 4.0);
  56955. }
  56956. effect.setFloat("totalStrength", _this.totalStrength);
  56957. effect.setFloat("radius", _this.radius);
  56958. effect.setFloat("area", _this.area);
  56959. effect.setFloat("fallOff", _this.fallOff);
  56960. effect.setFloat("base", _this.base);
  56961. effect.setTexture("textureSampler", _this._depthTexture);
  56962. effect.setTexture("randomSampler", _this._randomTexture);
  56963. };
  56964. };
  56965. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  56966. var _this = this;
  56967. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56968. this._ssaoCombinePostProcess.onApply = function (effect) {
  56969. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  56970. };
  56971. };
  56972. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  56973. var size = 512;
  56974. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56975. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56976. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56977. var context = this._randomTexture.getContext();
  56978. var rand = function (min, max) {
  56979. return Math.random() * (max - min) + min;
  56980. };
  56981. var randVector = BABYLON.Vector3.Zero();
  56982. for (var x = 0; x < size; x++) {
  56983. for (var y = 0; y < size; y++) {
  56984. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  56985. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  56986. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  56987. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  56988. context.fillRect(x, y, 1, 1);
  56989. }
  56990. }
  56991. this._randomTexture.update(false);
  56992. };
  56993. __decorate([
  56994. BABYLON.serialize()
  56995. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  56996. __decorate([
  56997. BABYLON.serialize()
  56998. ], SSAORenderingPipeline.prototype, "radius", void 0);
  56999. __decorate([
  57000. BABYLON.serialize()
  57001. ], SSAORenderingPipeline.prototype, "area", void 0);
  57002. __decorate([
  57003. BABYLON.serialize()
  57004. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57005. __decorate([
  57006. BABYLON.serialize()
  57007. ], SSAORenderingPipeline.prototype, "base", void 0);
  57008. __decorate([
  57009. BABYLON.serialize()
  57010. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57011. return SSAORenderingPipeline;
  57012. }(BABYLON.PostProcessRenderPipeline));
  57013. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57014. })(BABYLON || (BABYLON = {}));
  57015. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57016. var BABYLON;
  57017. (function (BABYLON) {
  57018. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57019. __extends(SSAO2RenderingPipeline, _super);
  57020. /**
  57021. * @constructor
  57022. * @param {string} name - The rendering pipeline name
  57023. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57024. * @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 }
  57025. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57026. */
  57027. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57028. var _this = _super.call(this, scene.getEngine(), name) || this;
  57029. // Members
  57030. /**
  57031. * The PassPostProcess id in the pipeline that contains the original scene color
  57032. * @type {string}
  57033. */
  57034. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57035. /**
  57036. * The SSAO PostProcess id in the pipeline
  57037. * @type {string}
  57038. */
  57039. _this.SSAORenderEffect = "SSAORenderEffect";
  57040. /**
  57041. * The horizontal blur PostProcess id in the pipeline
  57042. * @type {string}
  57043. */
  57044. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57045. /**
  57046. * The vertical blur PostProcess id in the pipeline
  57047. * @type {string}
  57048. */
  57049. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57050. /**
  57051. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57052. * @type {string}
  57053. */
  57054. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57055. /**
  57056. * The output strength of the SSAO post-process. Default value is 1.0.
  57057. * @type {number}
  57058. */
  57059. _this.totalStrength = 1.0;
  57060. /**
  57061. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57062. * @type {number}
  57063. */
  57064. _this.maxZ = 100.0;
  57065. /**
  57066. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57067. * @type {number}
  57068. */
  57069. _this.minZAspect = 0.2;
  57070. /**
  57071. * Number of samples used for the SSAO calculations. Default value is 8
  57072. * @type {number}
  57073. */
  57074. _this._samples = 8;
  57075. /**
  57076. * Are we using bilateral blur ?
  57077. * @type {boolean}
  57078. */
  57079. _this._expensiveBlur = true;
  57080. /**
  57081. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57082. * @type {number}
  57083. */
  57084. _this.radius = 2.0;
  57085. /**
  57086. * The base color of the SSAO post-process
  57087. * The final result is "base + ssao" between [0, 1]
  57088. * @type {number}
  57089. */
  57090. _this.base = 0.1;
  57091. _this._firstUpdate = true;
  57092. _this._scene = scene;
  57093. if (!_this.isSupported) {
  57094. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57095. return _this;
  57096. }
  57097. var ssaoRatio = ratio.ssaoRatio || ratio;
  57098. var blurRatio = ratio.blurRatio || ratio;
  57099. _this._ratio = {
  57100. ssaoRatio: ssaoRatio,
  57101. blurRatio: blurRatio
  57102. };
  57103. // Set up assets
  57104. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57105. _this._createRandomTexture();
  57106. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57107. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57108. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57109. _this._createSSAOPostProcess(1.0);
  57110. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57111. _this._createSSAOCombinePostProcess(blurRatio);
  57112. // Set up pipeline
  57113. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57114. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57115. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57116. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57117. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57118. // Finish
  57119. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57120. if (cameras)
  57121. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57122. return _this;
  57123. }
  57124. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57125. get: function () {
  57126. return this._samples;
  57127. },
  57128. set: function (n) {
  57129. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57130. this._samples = n;
  57131. this._sampleSphere = this._generateHemisphere();
  57132. this._firstUpdate = true;
  57133. },
  57134. enumerable: true,
  57135. configurable: true
  57136. });
  57137. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57138. get: function () {
  57139. return this._expensiveBlur;
  57140. },
  57141. set: function (b) {
  57142. 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"]);
  57143. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57144. this._expensiveBlur = b;
  57145. this._firstUpdate = true;
  57146. },
  57147. enumerable: true,
  57148. configurable: true
  57149. });
  57150. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57151. /**
  57152. * Support test.
  57153. * @type {boolean}
  57154. */
  57155. get: function () {
  57156. var engine = BABYLON.Engine.LastCreatedEngine;
  57157. if (!engine) {
  57158. return false;
  57159. }
  57160. return engine.getCaps().drawBuffersExtension;
  57161. },
  57162. enumerable: true,
  57163. configurable: true
  57164. });
  57165. // Public Methods
  57166. /**
  57167. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57168. */
  57169. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57170. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57171. for (var i = 0; i < this._scene.cameras.length; i++) {
  57172. var camera = this._scene.cameras[i];
  57173. this._originalColorPostProcess.dispose(camera);
  57174. this._ssaoPostProcess.dispose(camera);
  57175. this._blurHPostProcess.dispose(camera);
  57176. this._blurVPostProcess.dispose(camera);
  57177. this._ssaoCombinePostProcess.dispose(camera);
  57178. }
  57179. this._randomTexture.dispose();
  57180. if (disableGeometryBufferRenderer)
  57181. this._scene.disableGeometryBufferRenderer();
  57182. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57183. _super.prototype.dispose.call(this);
  57184. };
  57185. // Private Methods
  57186. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57187. var _this = this;
  57188. this._samplerOffsets = [];
  57189. var expensive = this.expensiveBlur;
  57190. for (var i = -8; i < 8; i++) {
  57191. this._samplerOffsets.push(i * 2 + 0.5);
  57192. }
  57193. 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");
  57194. this._blurHPostProcess.onApply = function (effect) {
  57195. if (!_this._scene.activeCamera) {
  57196. return;
  57197. }
  57198. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57199. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57200. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57201. effect.setFloat("radius", _this.radius);
  57202. effect.setTexture("depthSampler", _this._depthTexture);
  57203. if (_this._firstUpdate) {
  57204. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57205. }
  57206. };
  57207. 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");
  57208. this._blurVPostProcess.onApply = function (effect) {
  57209. if (!_this._scene.activeCamera) {
  57210. return;
  57211. }
  57212. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57213. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57214. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57215. effect.setFloat("radius", _this.radius);
  57216. effect.setTexture("depthSampler", _this._depthTexture);
  57217. if (_this._firstUpdate) {
  57218. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57219. _this._firstUpdate = false;
  57220. }
  57221. };
  57222. };
  57223. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57224. this._firstUpdate = true;
  57225. _super.prototype._rebuild.call(this);
  57226. };
  57227. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57228. var numSamples = this.samples;
  57229. var result = [];
  57230. var vector, scale;
  57231. var rand = function (min, max) {
  57232. return Math.random() * (max - min) + min;
  57233. };
  57234. var i = 0;
  57235. while (i < numSamples) {
  57236. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57237. vector.normalize();
  57238. scale = i / numSamples;
  57239. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57240. vector.scaleInPlace(scale);
  57241. result.push(vector.x, vector.y, vector.z);
  57242. i++;
  57243. }
  57244. return result;
  57245. };
  57246. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57247. var _this = this;
  57248. var numSamples = this.samples;
  57249. this._sampleSphere = this._generateHemisphere();
  57250. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57251. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57252. "base", "range", "projection", "near", "far", "texelSize",
  57253. "xViewport", "yViewport", "maxZ", "minZAspect"
  57254. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57255. this._ssaoPostProcess.onApply = function (effect) {
  57256. if (_this._firstUpdate) {
  57257. effect.setArray3("sampleSphere", _this._sampleSphere);
  57258. effect.setFloat("randTextureTiles", 4.0);
  57259. }
  57260. if (!_this._scene.activeCamera) {
  57261. return;
  57262. }
  57263. effect.setFloat("samplesFactor", 1 / _this.samples);
  57264. effect.setFloat("totalStrength", _this.totalStrength);
  57265. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57266. effect.setFloat("radius", _this.radius);
  57267. effect.setFloat("maxZ", _this.maxZ);
  57268. effect.setFloat("minZAspect", _this.minZAspect);
  57269. effect.setFloat("base", _this.base);
  57270. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57271. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57272. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57273. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57274. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57275. effect.setTexture("textureSampler", _this._depthTexture);
  57276. effect.setTexture("normalSampler", _this._normalTexture);
  57277. effect.setTexture("randomSampler", _this._randomTexture);
  57278. };
  57279. };
  57280. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57281. var _this = this;
  57282. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57283. this._ssaoCombinePostProcess.onApply = function (effect) {
  57284. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57285. };
  57286. };
  57287. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57288. var size = 512;
  57289. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57290. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57291. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57292. var context = this._randomTexture.getContext();
  57293. var rand = function (min, max) {
  57294. return Math.random() * (max - min) + min;
  57295. };
  57296. var randVector = BABYLON.Vector3.Zero();
  57297. for (var x = 0; x < size; x++) {
  57298. for (var y = 0; y < size; y++) {
  57299. randVector.x = rand(0.0, 1.0);
  57300. randVector.y = rand(0.0, 1.0);
  57301. randVector.z = 0.0;
  57302. randVector.normalize();
  57303. randVector.scaleInPlace(255);
  57304. randVector.x = Math.floor(randVector.x);
  57305. randVector.y = Math.floor(randVector.y);
  57306. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57307. context.fillRect(x, y, 1, 1);
  57308. }
  57309. }
  57310. this._randomTexture.update(false);
  57311. };
  57312. __decorate([
  57313. BABYLON.serialize()
  57314. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57315. __decorate([
  57316. BABYLON.serialize()
  57317. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57318. __decorate([
  57319. BABYLON.serialize()
  57320. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57321. __decorate([
  57322. BABYLON.serialize("samples")
  57323. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57324. __decorate([
  57325. BABYLON.serialize("expensiveBlur")
  57326. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57327. __decorate([
  57328. BABYLON.serialize()
  57329. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57330. __decorate([
  57331. BABYLON.serialize()
  57332. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57333. __decorate([
  57334. BABYLON.serialize()
  57335. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57336. return SSAO2RenderingPipeline;
  57337. }(BABYLON.PostProcessRenderPipeline));
  57338. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57339. })(BABYLON || (BABYLON = {}));
  57340. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57341. // BABYLON.JS Chromatic Aberration GLSL Shader
  57342. // Author: Olivier Guyot
  57343. // Separates very slightly R, G and B colors on the edges of the screen
  57344. // Inspired by Francois Tarlier & Martins Upitis
  57345. var BABYLON;
  57346. (function (BABYLON) {
  57347. var LensRenderingPipeline = /** @class */ (function (_super) {
  57348. __extends(LensRenderingPipeline, _super);
  57349. /**
  57350. * @constructor
  57351. *
  57352. * Effect parameters are as follow:
  57353. * {
  57354. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57355. * edge_blur: number; // from 0 to x (1 for realism)
  57356. * distortion: number; // from 0 to x (1 for realism)
  57357. * grain_amount: number; // from 0 to 1
  57358. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57359. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57360. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57361. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57362. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57363. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57364. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57365. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57366. * }
  57367. * Note: if an effect parameter is unset, effect is disabled
  57368. *
  57369. * @param {string} name - The rendering pipeline name
  57370. * @param {object} parameters - An object containing all parameters (see above)
  57371. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57372. * @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)
  57373. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57374. */
  57375. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57376. if (ratio === void 0) { ratio = 1.0; }
  57377. var _this = _super.call(this, scene.getEngine(), name) || this;
  57378. // Lens effects can be of the following:
  57379. // - chromatic aberration (slight shift of RGB colors)
  57380. // - blur on the edge of the lens
  57381. // - lens distortion
  57382. // - depth-of-field blur & highlights enhancing
  57383. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57384. // - grain effect (noise or custom texture)
  57385. // Two additional texture samplers are needed:
  57386. // - depth map (for depth-of-field)
  57387. // - grain texture
  57388. /**
  57389. * The chromatic aberration PostProcess id in the pipeline
  57390. * @type {string}
  57391. */
  57392. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57393. /**
  57394. * The highlights enhancing PostProcess id in the pipeline
  57395. * @type {string}
  57396. */
  57397. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57398. /**
  57399. * The depth-of-field PostProcess id in the pipeline
  57400. * @type {string}
  57401. */
  57402. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57403. _this._scene = scene;
  57404. // Fetch texture samplers
  57405. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57406. if (parameters.grain_texture) {
  57407. _this._grainTexture = parameters.grain_texture;
  57408. }
  57409. else {
  57410. _this._createGrainTexture();
  57411. }
  57412. // save parameters
  57413. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57414. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57415. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57416. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57417. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57418. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57419. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57420. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57421. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57422. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57423. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57424. // Create effects
  57425. _this._createChromaticAberrationPostProcess(ratio);
  57426. _this._createHighlightsPostProcess(ratio);
  57427. _this._createDepthOfFieldPostProcess(ratio / 4);
  57428. // Set up pipeline
  57429. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57430. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57431. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57432. if (_this._highlightsGain === -1) {
  57433. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57434. }
  57435. // Finish
  57436. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57437. if (cameras) {
  57438. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57439. }
  57440. return _this;
  57441. }
  57442. // public methods (self explanatory)
  57443. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57444. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57445. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57446. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57447. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57448. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57449. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57450. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57451. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57452. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57453. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57454. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57455. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57456. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57457. };
  57458. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57459. this._highlightsPostProcess.updateEffect();
  57460. };
  57461. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57462. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57463. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57464. this._highlightsGain = amount;
  57465. };
  57466. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57467. if (this._highlightsGain === -1) {
  57468. this._highlightsGain = 1.0;
  57469. }
  57470. this._highlightsThreshold = amount;
  57471. };
  57472. LensRenderingPipeline.prototype.disableHighlights = function () {
  57473. this._highlightsGain = -1;
  57474. };
  57475. /**
  57476. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57477. */
  57478. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57479. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57480. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57481. this._chromaticAberrationPostProcess = null;
  57482. this._highlightsPostProcess = null;
  57483. this._depthOfFieldPostProcess = null;
  57484. this._grainTexture.dispose();
  57485. if (disableDepthRender)
  57486. this._scene.disableDepthRenderer();
  57487. };
  57488. // colors shifting and distortion
  57489. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57490. var _this = this;
  57491. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57492. [], // samplers
  57493. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57494. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57495. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57496. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57497. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57498. };
  57499. };
  57500. // highlights enhancing
  57501. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57502. var _this = this;
  57503. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57504. [], // samplers
  57505. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57506. this._highlightsPostProcess.onApply = function (effect) {
  57507. effect.setFloat('gain', _this._highlightsGain);
  57508. effect.setFloat('threshold', _this._highlightsThreshold);
  57509. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57510. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57511. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57512. };
  57513. };
  57514. // colors shifting and distortion
  57515. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  57516. var _this = this;
  57517. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  57518. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  57519. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  57520. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57521. this._depthOfFieldPostProcess.onApply = function (effect) {
  57522. effect.setTexture("depthSampler", _this._depthTexture);
  57523. effect.setTexture("grainSampler", _this._grainTexture);
  57524. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  57525. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  57526. effect.setFloat('grain_amount', _this._grainAmount);
  57527. effect.setBool('blur_noise', _this._blurNoise);
  57528. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57529. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57530. effect.setFloat('distortion', _this._distortion);
  57531. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  57532. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  57533. effect.setFloat('aperture', _this._dofAperture);
  57534. effect.setFloat('darken', _this._dofDarken);
  57535. effect.setFloat('edge_blur', _this._edgeBlur);
  57536. effect.setBool('highlights', (_this._highlightsGain !== -1));
  57537. if (_this._scene.activeCamera) {
  57538. effect.setFloat('near', _this._scene.activeCamera.minZ);
  57539. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  57540. }
  57541. };
  57542. };
  57543. // creates a black and white random noise texture, 512x512
  57544. LensRenderingPipeline.prototype._createGrainTexture = function () {
  57545. var size = 512;
  57546. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57547. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57548. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57549. var context = this._grainTexture.getContext();
  57550. var rand = function (min, max) {
  57551. return Math.random() * (max - min) + min;
  57552. };
  57553. var value;
  57554. for (var x = 0; x < size; x++) {
  57555. for (var y = 0; y < size; y++) {
  57556. value = Math.floor(rand(0.42, 0.58) * 255);
  57557. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  57558. context.fillRect(x, y, 1, 1);
  57559. }
  57560. }
  57561. this._grainTexture.update(false);
  57562. };
  57563. return LensRenderingPipeline;
  57564. }(BABYLON.PostProcessRenderPipeline));
  57565. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  57566. })(BABYLON || (BABYLON = {}));
  57567. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  57568. var BABYLON;
  57569. (function (BABYLON) {
  57570. var StandardRenderingPipeline = /** @class */ (function (_super) {
  57571. __extends(StandardRenderingPipeline, _super);
  57572. /**
  57573. * @constructor
  57574. * @param {string} name - The rendering pipeline name
  57575. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57576. * @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)
  57577. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57578. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57579. */
  57580. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57581. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57582. var _this = _super.call(this, scene.getEngine(), name) || this;
  57583. _this.downSampleX4PostProcess = null;
  57584. _this.brightPassPostProcess = null;
  57585. _this.blurHPostProcesses = [];
  57586. _this.blurVPostProcesses = [];
  57587. _this.textureAdderPostProcess = null;
  57588. _this.volumetricLightPostProcess = null;
  57589. _this.volumetricLightSmoothXPostProcess = null;
  57590. _this.volumetricLightSmoothYPostProcess = null;
  57591. _this.volumetricLightMergePostProces = null;
  57592. _this.volumetricLightFinalPostProcess = null;
  57593. _this.luminancePostProcess = null;
  57594. _this.luminanceDownSamplePostProcesses = [];
  57595. _this.hdrPostProcess = null;
  57596. _this.textureAdderFinalPostProcess = null;
  57597. _this.lensFlareFinalPostProcess = null;
  57598. _this.hdrFinalPostProcess = null;
  57599. _this.lensFlarePostProcess = null;
  57600. _this.lensFlareComposePostProcess = null;
  57601. _this.motionBlurPostProcess = null;
  57602. _this.depthOfFieldPostProcess = null;
  57603. // Values
  57604. _this.brightThreshold = 1.0;
  57605. _this.blurWidth = 512.0;
  57606. _this.horizontalBlur = false;
  57607. _this.exposure = 1.0;
  57608. _this.lensTexture = null;
  57609. _this.volumetricLightCoefficient = 0.2;
  57610. _this.volumetricLightPower = 4.0;
  57611. _this.volumetricLightBlurScale = 64.0;
  57612. _this.sourceLight = null;
  57613. _this.hdrMinimumLuminance = 1.0;
  57614. _this.hdrDecreaseRate = 0.5;
  57615. _this.hdrIncreaseRate = 0.5;
  57616. _this.lensColorTexture = null;
  57617. _this.lensFlareStrength = 20.0;
  57618. _this.lensFlareGhostDispersal = 1.4;
  57619. _this.lensFlareHaloWidth = 0.7;
  57620. _this.lensFlareDistortionStrength = 16.0;
  57621. _this.lensStarTexture = null;
  57622. _this.lensFlareDirtTexture = null;
  57623. _this.depthOfFieldDistance = 10.0;
  57624. _this.depthOfFieldBlurWidth = 64.0;
  57625. _this.motionStrength = 1.0;
  57626. // IAnimatable
  57627. _this.animations = [];
  57628. _this._currentDepthOfFieldSource = null;
  57629. _this._hdrCurrentLuminance = 1.0;
  57630. // Getters and setters
  57631. _this._bloomEnabled = true;
  57632. _this._depthOfFieldEnabled = false;
  57633. _this._vlsEnabled = false;
  57634. _this._lensFlareEnabled = false;
  57635. _this._hdrEnabled = false;
  57636. _this._motionBlurEnabled = false;
  57637. _this._motionBlurSamples = 64.0;
  57638. _this._volumetricLightStepsCount = 50.0;
  57639. _this._cameras = cameras || [];
  57640. // Initialize
  57641. _this._scene = scene;
  57642. _this._basePostProcess = originalPostProcess;
  57643. _this._ratio = ratio;
  57644. // Misc
  57645. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57646. // Finish
  57647. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57648. _this._buildPipeline();
  57649. return _this;
  57650. }
  57651. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  57652. get: function () {
  57653. return this._bloomEnabled;
  57654. },
  57655. set: function (enabled) {
  57656. if (this._bloomEnabled === enabled) {
  57657. return;
  57658. }
  57659. this._bloomEnabled = enabled;
  57660. this._buildPipeline();
  57661. },
  57662. enumerable: true,
  57663. configurable: true
  57664. });
  57665. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57666. get: function () {
  57667. return this._depthOfFieldEnabled;
  57668. },
  57669. set: function (enabled) {
  57670. if (this._depthOfFieldEnabled === enabled) {
  57671. return;
  57672. }
  57673. this._depthOfFieldEnabled = enabled;
  57674. this._buildPipeline();
  57675. },
  57676. enumerable: true,
  57677. configurable: true
  57678. });
  57679. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57680. get: function () {
  57681. return this._lensFlareEnabled;
  57682. },
  57683. set: function (enabled) {
  57684. if (this._lensFlareEnabled === enabled) {
  57685. return;
  57686. }
  57687. this._lensFlareEnabled = enabled;
  57688. this._buildPipeline();
  57689. },
  57690. enumerable: true,
  57691. configurable: true
  57692. });
  57693. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  57694. get: function () {
  57695. return this._hdrEnabled;
  57696. },
  57697. set: function (enabled) {
  57698. if (this._hdrEnabled === enabled) {
  57699. return;
  57700. }
  57701. this._hdrEnabled = enabled;
  57702. this._buildPipeline();
  57703. },
  57704. enumerable: true,
  57705. configurable: true
  57706. });
  57707. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  57708. get: function () {
  57709. return this._vlsEnabled;
  57710. },
  57711. set: function (enabled) {
  57712. if (this._vlsEnabled === enabled) {
  57713. return;
  57714. }
  57715. if (enabled) {
  57716. var geometry = this._scene.enableGeometryBufferRenderer();
  57717. if (!geometry) {
  57718. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  57719. return;
  57720. }
  57721. }
  57722. this._vlsEnabled = enabled;
  57723. this._buildPipeline();
  57724. },
  57725. enumerable: true,
  57726. configurable: true
  57727. });
  57728. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  57729. get: function () {
  57730. return this._motionBlurEnabled;
  57731. },
  57732. set: function (enabled) {
  57733. if (this._motionBlurEnabled === enabled) {
  57734. return;
  57735. }
  57736. this._motionBlurEnabled = enabled;
  57737. this._buildPipeline();
  57738. },
  57739. enumerable: true,
  57740. configurable: true
  57741. });
  57742. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  57743. get: function () {
  57744. return this._volumetricLightStepsCount;
  57745. },
  57746. set: function (count) {
  57747. if (this.volumetricLightPostProcess) {
  57748. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  57749. }
  57750. this._volumetricLightStepsCount = count;
  57751. },
  57752. enumerable: true,
  57753. configurable: true
  57754. });
  57755. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  57756. get: function () {
  57757. return this._motionBlurSamples;
  57758. },
  57759. set: function (samples) {
  57760. if (this.motionBlurPostProcess) {
  57761. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  57762. }
  57763. this._motionBlurSamples = samples;
  57764. },
  57765. enumerable: true,
  57766. configurable: true
  57767. });
  57768. StandardRenderingPipeline.prototype._buildPipeline = function () {
  57769. var _this = this;
  57770. var ratio = this._ratio;
  57771. var scene = this._scene;
  57772. this._disposePostProcesses();
  57773. this._reset();
  57774. // Create pass post-process
  57775. if (!this._basePostProcess) {
  57776. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  57777. this.originalPostProcess.onApply = function (effect) {
  57778. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  57779. };
  57780. }
  57781. else {
  57782. this.originalPostProcess = this._basePostProcess;
  57783. }
  57784. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  57785. this._currentDepthOfFieldSource = this.originalPostProcess;
  57786. if (this._vlsEnabled) {
  57787. // Create volumetric light
  57788. this._createVolumetricLightPostProcess(scene, ratio);
  57789. // Create volumetric light final post-process
  57790. 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);
  57791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  57792. }
  57793. if (this._bloomEnabled) {
  57794. // Create down sample X4 post-process
  57795. this._createDownSampleX4PostProcess(scene, ratio / 2);
  57796. // Create bright pass post-process
  57797. this._createBrightPassPostProcess(scene, ratio / 2);
  57798. // Create gaussian blur post-processes (down sampling blurs)
  57799. this._createBlurPostProcesses(scene, ratio / 4, 1);
  57800. // Create texture adder post-process
  57801. this._createTextureAdderPostProcess(scene, ratio);
  57802. // Create depth-of-field source post-process
  57803. 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);
  57804. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  57805. }
  57806. if (this._lensFlareEnabled) {
  57807. // Create lens flare post-process
  57808. this._createLensFlarePostProcess(scene, ratio);
  57809. // Create depth-of-field source post-process post lens-flare and disable it now
  57810. 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);
  57811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  57812. }
  57813. if (this._hdrEnabled) {
  57814. // Create luminance
  57815. this._createLuminancePostProcesses(scene, this._floatTextureType);
  57816. // Create HDR
  57817. this._createHdrPostProcess(scene, ratio);
  57818. // Create depth-of-field source post-process post hdr and disable it now
  57819. 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);
  57820. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  57821. }
  57822. if (this._depthOfFieldEnabled) {
  57823. // Create gaussian blur used by depth-of-field
  57824. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  57825. // Create depth-of-field post-process
  57826. this._createDepthOfFieldPostProcess(scene, ratio);
  57827. }
  57828. if (this._motionBlurEnabled) {
  57829. // Create motion blur post-process
  57830. this._createMotionBlurPostProcess(scene, ratio);
  57831. }
  57832. if (this._cameras !== null) {
  57833. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  57834. }
  57835. };
  57836. // Down Sample X4 Post-Processs
  57837. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  57838. var _this = this;
  57839. var downSampleX4Offsets = new Array(32);
  57840. 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);
  57841. this.downSampleX4PostProcess.onApply = function (effect) {
  57842. var id = 0;
  57843. var width = _this.downSampleX4PostProcess.width;
  57844. var height = _this.downSampleX4PostProcess.height;
  57845. for (var i = -2; i < 2; i++) {
  57846. for (var j = -2; j < 2; j++) {
  57847. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  57848. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  57849. id += 2;
  57850. }
  57851. }
  57852. effect.setArray2("dsOffsets", downSampleX4Offsets);
  57853. };
  57854. // Add to pipeline
  57855. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  57856. };
  57857. // Brightpass Post-Process
  57858. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  57859. var _this = this;
  57860. var brightOffsets = new Array(8);
  57861. 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);
  57862. this.brightPassPostProcess.onApply = function (effect) {
  57863. var sU = (1.0 / _this.brightPassPostProcess.width);
  57864. var sV = (1.0 / _this.brightPassPostProcess.height);
  57865. brightOffsets[0] = -0.5 * sU;
  57866. brightOffsets[1] = 0.5 * sV;
  57867. brightOffsets[2] = 0.5 * sU;
  57868. brightOffsets[3] = 0.5 * sV;
  57869. brightOffsets[4] = -0.5 * sU;
  57870. brightOffsets[5] = -0.5 * sV;
  57871. brightOffsets[6] = 0.5 * sU;
  57872. brightOffsets[7] = -0.5 * sV;
  57873. effect.setArray2("dsOffsets", brightOffsets);
  57874. effect.setFloat("brightThreshold", _this.brightThreshold);
  57875. };
  57876. // Add to pipeline
  57877. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  57878. };
  57879. // Create blur H&V post-processes
  57880. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  57881. var _this = this;
  57882. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  57883. var engine = scene.getEngine();
  57884. 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);
  57885. 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);
  57886. blurX.onActivateObservable.add(function () {
  57887. var dw = blurX.width / engine.getRenderWidth();
  57888. blurX.kernel = _this[blurWidthKey] * dw;
  57889. });
  57890. blurY.onActivateObservable.add(function () {
  57891. var dw = blurY.height / engine.getRenderHeight();
  57892. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  57893. });
  57894. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  57895. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  57896. this.blurHPostProcesses.push(blurX);
  57897. this.blurVPostProcesses.push(blurY);
  57898. };
  57899. // Create texture adder post-process
  57900. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  57901. var _this = this;
  57902. 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);
  57903. this.textureAdderPostProcess.onApply = function (effect) {
  57904. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  57905. effect.setTexture("lensSampler", _this.lensTexture);
  57906. effect.setFloat("exposure", _this.exposure);
  57907. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  57908. };
  57909. // Add to pipeline
  57910. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  57911. };
  57912. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  57913. var _this = this;
  57914. var geometryRenderer = scene.enableGeometryBufferRenderer();
  57915. geometryRenderer.enablePosition = true;
  57916. var geometry = geometryRenderer.getGBuffer();
  57917. // Base post-process
  57918. 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));
  57919. var depthValues = BABYLON.Vector2.Zero();
  57920. this.volumetricLightPostProcess.onApply = function (effect) {
  57921. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  57922. var generator = _this.sourceLight.getShadowGenerator();
  57923. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  57924. effect.setTexture("positionSampler", geometry.textures[2]);
  57925. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  57926. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  57927. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  57928. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  57929. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  57930. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  57931. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  57932. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  57933. effect.setVector2("depthValues", depthValues);
  57934. }
  57935. };
  57936. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  57937. // Smooth
  57938. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  57939. // Merge
  57940. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  57941. this.volumetricLightMergePostProces.onApply = function (effect) {
  57942. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  57943. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  57944. };
  57945. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  57946. };
  57947. // Create luminance
  57948. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  57949. var _this = this;
  57950. // Create luminance
  57951. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  57952. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  57953. var offsets = [];
  57954. this.luminancePostProcess.onApply = function (effect) {
  57955. var sU = (1.0 / _this.luminancePostProcess.width);
  57956. var sV = (1.0 / _this.luminancePostProcess.height);
  57957. offsets[0] = -0.5 * sU;
  57958. offsets[1] = 0.5 * sV;
  57959. offsets[2] = 0.5 * sU;
  57960. offsets[3] = 0.5 * sV;
  57961. offsets[4] = -0.5 * sU;
  57962. offsets[5] = -0.5 * sV;
  57963. offsets[6] = 0.5 * sU;
  57964. offsets[7] = -0.5 * sV;
  57965. effect.setArray2("lumOffsets", offsets);
  57966. };
  57967. // Add to pipeline
  57968. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  57969. // Create down sample luminance
  57970. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  57971. var size = Math.pow(3, i);
  57972. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  57973. if (i === 0) {
  57974. defines += "#define FINAL_DOWN_SAMPLER";
  57975. }
  57976. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  57977. this.luminanceDownSamplePostProcesses.push(postProcess);
  57978. }
  57979. // Create callbacks and add effects
  57980. var lastLuminance = this.luminancePostProcess;
  57981. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  57982. var downSampleOffsets = new Array(18);
  57983. pp.onApply = function (effect) {
  57984. if (!lastLuminance) {
  57985. return;
  57986. }
  57987. var id = 0;
  57988. for (var x = -1; x < 2; x++) {
  57989. for (var y = -1; y < 2; y++) {
  57990. downSampleOffsets[id] = x / lastLuminance.width;
  57991. downSampleOffsets[id + 1] = y / lastLuminance.height;
  57992. id += 2;
  57993. }
  57994. }
  57995. effect.setArray2("dsOffsets", downSampleOffsets);
  57996. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  57997. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  57998. lastLuminance = _this.luminancePostProcess;
  57999. }
  58000. else {
  58001. lastLuminance = pp;
  58002. }
  58003. };
  58004. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58005. pp.onAfterRender = function (effect) {
  58006. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58007. 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);
  58008. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58009. };
  58010. }
  58011. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58012. });
  58013. };
  58014. // Create HDR post-process
  58015. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58016. var _this = this;
  58017. 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);
  58018. var outputLiminance = 1;
  58019. var time = 0;
  58020. var lastTime = 0;
  58021. this.hdrPostProcess.onApply = function (effect) {
  58022. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58023. time += scene.getEngine().getDeltaTime();
  58024. if (outputLiminance < 0) {
  58025. outputLiminance = _this._hdrCurrentLuminance;
  58026. }
  58027. else {
  58028. var dt = (lastTime - time) / 1000.0;
  58029. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58030. outputLiminance += _this.hdrDecreaseRate * dt;
  58031. }
  58032. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58033. outputLiminance -= _this.hdrIncreaseRate * dt;
  58034. }
  58035. else {
  58036. outputLiminance = _this._hdrCurrentLuminance;
  58037. }
  58038. }
  58039. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58040. effect.setFloat("averageLuminance", outputLiminance);
  58041. lastTime = time;
  58042. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58043. };
  58044. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58045. };
  58046. // Create lens flare post-process
  58047. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58048. var _this = this;
  58049. 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);
  58050. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58051. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58052. 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);
  58053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58054. var resolution = new BABYLON.Vector2(0, 0);
  58055. // Lens flare
  58056. this.lensFlarePostProcess.onApply = function (effect) {
  58057. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58058. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58059. effect.setFloat("strength", _this.lensFlareStrength);
  58060. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58061. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58062. // Shift
  58063. resolution.x = _this.lensFlarePostProcess.width;
  58064. resolution.y = _this.lensFlarePostProcess.height;
  58065. effect.setVector2("resolution", resolution);
  58066. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58067. };
  58068. // Compose
  58069. 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);
  58070. 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);
  58071. this.lensFlareComposePostProcess.onApply = function (effect) {
  58072. if (!_this._scene.activeCamera) {
  58073. return;
  58074. }
  58075. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58076. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58077. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58078. // Lens start rotation matrix
  58079. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58080. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58081. 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));
  58082. camRot *= 4.0;
  58083. 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);
  58084. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58085. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58086. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58087. };
  58088. };
  58089. // Create depth-of-field post-process
  58090. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58091. var _this = this;
  58092. 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);
  58093. this.depthOfFieldPostProcess.onApply = function (effect) {
  58094. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58095. effect.setTexture("depthSampler", _this._getDepthTexture());
  58096. effect.setFloat("distance", _this.depthOfFieldDistance);
  58097. };
  58098. // Add to pipeline
  58099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58100. };
  58101. // Create motion blur post-process
  58102. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58103. var _this = this;
  58104. 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);
  58105. var motionScale = 0;
  58106. var prevViewProjection = BABYLON.Matrix.Identity();
  58107. var invViewProjection = BABYLON.Matrix.Identity();
  58108. var viewProjection = BABYLON.Matrix.Identity();
  58109. var screenSize = BABYLON.Vector2.Zero();
  58110. this.motionBlurPostProcess.onApply = function (effect) {
  58111. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58112. viewProjection.invertToRef(invViewProjection);
  58113. effect.setMatrix("inverseViewProjection", invViewProjection);
  58114. effect.setMatrix("prevViewProjection", prevViewProjection);
  58115. prevViewProjection = viewProjection;
  58116. screenSize.x = _this.motionBlurPostProcess.width;
  58117. screenSize.y = _this.motionBlurPostProcess.height;
  58118. effect.setVector2("screenSize", screenSize);
  58119. motionScale = scene.getEngine().getFps() / 60.0;
  58120. effect.setFloat("motionScale", motionScale);
  58121. effect.setFloat("motionStrength", _this.motionStrength);
  58122. effect.setTexture("depthSampler", _this._getDepthTexture());
  58123. };
  58124. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58125. };
  58126. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58127. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58128. var renderer = this._scene.enableGeometryBufferRenderer();
  58129. return renderer.getGBuffer().textures[0];
  58130. }
  58131. return this._scene.enableDepthRenderer().getDepthMap();
  58132. };
  58133. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58134. for (var i = 0; i < this._cameras.length; i++) {
  58135. var camera = this._cameras[i];
  58136. if (this.originalPostProcess) {
  58137. this.originalPostProcess.dispose(camera);
  58138. }
  58139. if (this.downSampleX4PostProcess) {
  58140. this.downSampleX4PostProcess.dispose(camera);
  58141. }
  58142. if (this.brightPassPostProcess) {
  58143. this.brightPassPostProcess.dispose(camera);
  58144. }
  58145. if (this.textureAdderPostProcess) {
  58146. this.textureAdderPostProcess.dispose(camera);
  58147. }
  58148. if (this.textureAdderFinalPostProcess) {
  58149. this.textureAdderFinalPostProcess.dispose(camera);
  58150. }
  58151. if (this.volumetricLightPostProcess) {
  58152. this.volumetricLightPostProcess.dispose(camera);
  58153. }
  58154. if (this.volumetricLightSmoothXPostProcess) {
  58155. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58156. }
  58157. if (this.volumetricLightSmoothYPostProcess) {
  58158. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58159. }
  58160. if (this.volumetricLightMergePostProces) {
  58161. this.volumetricLightMergePostProces.dispose(camera);
  58162. }
  58163. if (this.volumetricLightFinalPostProcess) {
  58164. this.volumetricLightFinalPostProcess.dispose(camera);
  58165. }
  58166. if (this.lensFlarePostProcess) {
  58167. this.lensFlarePostProcess.dispose(camera);
  58168. }
  58169. if (this.lensFlareComposePostProcess) {
  58170. this.lensFlareComposePostProcess.dispose(camera);
  58171. }
  58172. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58173. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58174. }
  58175. if (this.luminancePostProcess) {
  58176. this.luminancePostProcess.dispose(camera);
  58177. }
  58178. if (this.hdrPostProcess) {
  58179. this.hdrPostProcess.dispose(camera);
  58180. }
  58181. if (this.hdrFinalPostProcess) {
  58182. this.hdrFinalPostProcess.dispose(camera);
  58183. }
  58184. if (this.depthOfFieldPostProcess) {
  58185. this.depthOfFieldPostProcess.dispose(camera);
  58186. }
  58187. if (this.motionBlurPostProcess) {
  58188. this.motionBlurPostProcess.dispose(camera);
  58189. }
  58190. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58191. this.blurHPostProcesses[j].dispose(camera);
  58192. }
  58193. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58194. this.blurVPostProcesses[j].dispose(camera);
  58195. }
  58196. }
  58197. this.originalPostProcess = null;
  58198. this.downSampleX4PostProcess = null;
  58199. this.brightPassPostProcess = null;
  58200. this.textureAdderPostProcess = null;
  58201. this.textureAdderFinalPostProcess = null;
  58202. this.volumetricLightPostProcess = null;
  58203. this.volumetricLightSmoothXPostProcess = null;
  58204. this.volumetricLightSmoothYPostProcess = null;
  58205. this.volumetricLightMergePostProces = null;
  58206. this.volumetricLightFinalPostProcess = null;
  58207. this.lensFlarePostProcess = null;
  58208. this.lensFlareComposePostProcess = null;
  58209. this.luminancePostProcess = null;
  58210. this.hdrPostProcess = null;
  58211. this.hdrFinalPostProcess = null;
  58212. this.depthOfFieldPostProcess = null;
  58213. this.motionBlurPostProcess = null;
  58214. this.luminanceDownSamplePostProcesses = [];
  58215. this.blurHPostProcesses = [];
  58216. this.blurVPostProcesses = [];
  58217. };
  58218. // Dispose
  58219. StandardRenderingPipeline.prototype.dispose = function () {
  58220. this._disposePostProcesses();
  58221. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58222. _super.prototype.dispose.call(this);
  58223. };
  58224. // Serialize rendering pipeline
  58225. StandardRenderingPipeline.prototype.serialize = function () {
  58226. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58227. serializationObject.customType = "StandardRenderingPipeline";
  58228. return serializationObject;
  58229. };
  58230. /**
  58231. * Static members
  58232. */
  58233. // Parse serialized pipeline
  58234. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58235. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58236. };
  58237. // Luminance steps
  58238. StandardRenderingPipeline.LuminanceSteps = 6;
  58239. __decorate([
  58240. BABYLON.serialize()
  58241. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58242. __decorate([
  58243. BABYLON.serialize()
  58244. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58245. __decorate([
  58246. BABYLON.serialize()
  58247. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58248. __decorate([
  58249. BABYLON.serialize()
  58250. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58251. __decorate([
  58252. BABYLON.serializeAsTexture("lensTexture")
  58253. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58254. __decorate([
  58255. BABYLON.serialize()
  58256. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58257. __decorate([
  58258. BABYLON.serialize()
  58259. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58260. __decorate([
  58261. BABYLON.serialize()
  58262. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58263. __decorate([
  58264. BABYLON.serialize()
  58265. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58266. __decorate([
  58267. BABYLON.serialize()
  58268. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58269. __decorate([
  58270. BABYLON.serialize()
  58271. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58272. __decorate([
  58273. BABYLON.serializeAsTexture("lensColorTexture")
  58274. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58275. __decorate([
  58276. BABYLON.serialize()
  58277. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58278. __decorate([
  58279. BABYLON.serialize()
  58280. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58281. __decorate([
  58282. BABYLON.serialize()
  58283. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58284. __decorate([
  58285. BABYLON.serialize()
  58286. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58287. __decorate([
  58288. BABYLON.serializeAsTexture("lensStarTexture")
  58289. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58290. __decorate([
  58291. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58292. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58293. __decorate([
  58294. BABYLON.serialize()
  58295. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58296. __decorate([
  58297. BABYLON.serialize()
  58298. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58299. __decorate([
  58300. BABYLON.serialize()
  58301. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58302. __decorate([
  58303. BABYLON.serialize()
  58304. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58305. __decorate([
  58306. BABYLON.serialize()
  58307. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58308. __decorate([
  58309. BABYLON.serialize()
  58310. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58311. __decorate([
  58312. BABYLON.serialize()
  58313. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58314. __decorate([
  58315. BABYLON.serialize()
  58316. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58317. __decorate([
  58318. BABYLON.serialize()
  58319. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58320. __decorate([
  58321. BABYLON.serialize()
  58322. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58323. __decorate([
  58324. BABYLON.serialize()
  58325. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58326. return StandardRenderingPipeline;
  58327. }(BABYLON.PostProcessRenderPipeline));
  58328. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58329. })(BABYLON || (BABYLON = {}));
  58330. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58331. var BABYLON;
  58332. (function (BABYLON) {
  58333. var FxaaPostProcess = /** @class */ (function (_super) {
  58334. __extends(FxaaPostProcess, _super);
  58335. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58336. if (camera === void 0) { camera = null; }
  58337. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58338. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58339. _this.onApplyObservable.add(function (effect) {
  58340. var texelSize = _this.texelSize;
  58341. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58342. });
  58343. return _this;
  58344. }
  58345. return FxaaPostProcess;
  58346. }(BABYLON.PostProcess));
  58347. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58348. })(BABYLON || (BABYLON = {}));
  58349. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58350. var BABYLON;
  58351. (function (BABYLON) {
  58352. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58353. __extends(DefaultRenderingPipeline, _super);
  58354. /**
  58355. * @constructor
  58356. * @param {string} name - The rendering pipeline name
  58357. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58358. * @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)
  58359. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58360. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58361. */
  58362. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58363. if (automaticBuild === void 0) { automaticBuild = true; }
  58364. var _this = _super.call(this, scene.getEngine(), name) || this;
  58365. _this.PassPostProcessId = "PassPostProcessEffect";
  58366. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58367. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58368. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58369. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58370. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58371. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58372. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58373. // IAnimatable
  58374. _this.animations = [];
  58375. // Values
  58376. _this._bloomEnabled = false;
  58377. _this._fxaaEnabled = false;
  58378. _this._imageProcessingEnabled = true;
  58379. _this._bloomScale = 0.6;
  58380. _this._buildAllowed = true;
  58381. /**
  58382. * Specifies the size of the bloom blur kernel, relative to the final output size
  58383. */
  58384. _this.bloomKernel = 64;
  58385. /**
  58386. * Specifies the weight of the bloom in the final rendering
  58387. */
  58388. _this._bloomWeight = 0.15;
  58389. _this._cameras = cameras || [];
  58390. _this._buildAllowed = automaticBuild;
  58391. // Initialize
  58392. _this._scene = scene;
  58393. var caps = _this._scene.getEngine().getCaps();
  58394. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58395. // Misc
  58396. if (_this._hdr) {
  58397. if (caps.textureHalfFloatRender) {
  58398. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58399. }
  58400. else if (caps.textureFloatRender) {
  58401. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58402. }
  58403. }
  58404. else {
  58405. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58406. }
  58407. // Attach
  58408. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58409. _this._buildPipeline();
  58410. return _this;
  58411. }
  58412. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58413. get: function () {
  58414. return this._bloomWeight;
  58415. },
  58416. set: function (value) {
  58417. if (this._bloomWeight === value) {
  58418. return;
  58419. }
  58420. this._bloomWeight = value;
  58421. if (this._hdr && this.copyBack) {
  58422. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58423. }
  58424. },
  58425. enumerable: true,
  58426. configurable: true
  58427. });
  58428. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58429. get: function () {
  58430. return this._bloomScale;
  58431. },
  58432. set: function (value) {
  58433. if (this._bloomScale === value) {
  58434. return;
  58435. }
  58436. this._bloomScale = value;
  58437. this._buildPipeline();
  58438. },
  58439. enumerable: true,
  58440. configurable: true
  58441. });
  58442. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58443. get: function () {
  58444. return this._bloomEnabled;
  58445. },
  58446. set: function (enabled) {
  58447. if (this._bloomEnabled === enabled) {
  58448. return;
  58449. }
  58450. this._bloomEnabled = enabled;
  58451. this._buildPipeline();
  58452. },
  58453. enumerable: true,
  58454. configurable: true
  58455. });
  58456. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58457. get: function () {
  58458. return this._fxaaEnabled;
  58459. },
  58460. set: function (enabled) {
  58461. if (this._fxaaEnabled === enabled) {
  58462. return;
  58463. }
  58464. this._fxaaEnabled = enabled;
  58465. this._buildPipeline();
  58466. },
  58467. enumerable: true,
  58468. configurable: true
  58469. });
  58470. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58471. get: function () {
  58472. return this._imageProcessingEnabled;
  58473. },
  58474. set: function (enabled) {
  58475. if (this._imageProcessingEnabled === enabled) {
  58476. return;
  58477. }
  58478. this._imageProcessingEnabled = enabled;
  58479. this._buildPipeline();
  58480. },
  58481. enumerable: true,
  58482. configurable: true
  58483. });
  58484. /**
  58485. * Force the compilation of the entire pipeline.
  58486. */
  58487. DefaultRenderingPipeline.prototype.prepare = function () {
  58488. var previousState = this._buildAllowed;
  58489. this._buildAllowed = true;
  58490. this._buildPipeline();
  58491. this._buildAllowed = previousState;
  58492. };
  58493. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58494. var _this = this;
  58495. if (!this._buildAllowed) {
  58496. return;
  58497. }
  58498. var engine = this._scene.getEngine();
  58499. this._disposePostProcesses();
  58500. this._reset();
  58501. if (this.bloomEnabled) {
  58502. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58503. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58504. if (!this._hdr) {
  58505. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58506. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58507. this.highlights.autoClear = false;
  58508. this.highlights.alwaysForcePOT = true;
  58509. }
  58510. 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);
  58511. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58512. this.blurX.alwaysForcePOT = true;
  58513. this.blurX.autoClear = false;
  58514. this.blurX.onActivateObservable.add(function () {
  58515. var dw = _this.blurX.width / engine.getRenderWidth(true);
  58516. _this.blurX.kernel = _this.bloomKernel * dw;
  58517. });
  58518. 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);
  58519. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  58520. this.blurY.alwaysForcePOT = true;
  58521. this.blurY.autoClear = false;
  58522. this.blurY.onActivateObservable.add(function () {
  58523. var dh = _this.blurY.height / engine.getRenderHeight(true);
  58524. _this.blurY.kernel = _this.bloomKernel * dh;
  58525. });
  58526. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58527. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  58528. this.copyBack.alwaysForcePOT = true;
  58529. if (this._hdr) {
  58530. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  58531. var w = this.bloomWeight;
  58532. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  58533. }
  58534. else {
  58535. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  58536. }
  58537. this.copyBack.autoClear = false;
  58538. }
  58539. if (this._imageProcessingEnabled) {
  58540. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58541. if (this._hdr) {
  58542. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  58543. }
  58544. else {
  58545. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  58546. }
  58547. }
  58548. if (this.fxaaEnabled) {
  58549. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58550. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  58551. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58552. }
  58553. else {
  58554. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58555. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  58556. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58557. }
  58558. if (this.bloomEnabled) {
  58559. if (this._hdr) {
  58560. this.copyBack.shareOutputWith(this.blurX);
  58561. if (this.imageProcessing) {
  58562. this.imageProcessing.shareOutputWith(this.pass);
  58563. this.imageProcessing.autoClear = false;
  58564. }
  58565. else if (this.fxaa) {
  58566. this.fxaa.shareOutputWith(this.pass);
  58567. }
  58568. else {
  58569. this.finalMerge.shareOutputWith(this.pass);
  58570. }
  58571. }
  58572. else {
  58573. if (this.fxaa) {
  58574. this.fxaa.shareOutputWith(this.pass);
  58575. }
  58576. else {
  58577. this.finalMerge.shareOutputWith(this.pass);
  58578. }
  58579. }
  58580. }
  58581. if (this._cameras !== null) {
  58582. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58583. }
  58584. };
  58585. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  58586. for (var i = 0; i < this._cameras.length; i++) {
  58587. var camera = this._cameras[i];
  58588. if (this.pass) {
  58589. this.pass.dispose(camera);
  58590. }
  58591. if (this.highlights) {
  58592. this.highlights.dispose(camera);
  58593. }
  58594. if (this.blurX) {
  58595. this.blurX.dispose(camera);
  58596. }
  58597. if (this.blurY) {
  58598. this.blurY.dispose(camera);
  58599. }
  58600. if (this.copyBack) {
  58601. this.copyBack.dispose(camera);
  58602. }
  58603. if (this.imageProcessing) {
  58604. this.imageProcessing.dispose(camera);
  58605. }
  58606. if (this.fxaa) {
  58607. this.fxaa.dispose(camera);
  58608. }
  58609. if (this.finalMerge) {
  58610. this.finalMerge.dispose(camera);
  58611. }
  58612. }
  58613. this.pass = null;
  58614. this.highlights = null;
  58615. this.blurX = null;
  58616. this.blurY = null;
  58617. this.copyBack = null;
  58618. this.imageProcessing = null;
  58619. this.fxaa = null;
  58620. this.finalMerge = null;
  58621. };
  58622. // Dispose
  58623. DefaultRenderingPipeline.prototype.dispose = function () {
  58624. this._disposePostProcesses();
  58625. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58626. _super.prototype.dispose.call(this);
  58627. };
  58628. // Serialize rendering pipeline
  58629. DefaultRenderingPipeline.prototype.serialize = function () {
  58630. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58631. serializationObject.customType = "DefaultRenderingPipeline";
  58632. return serializationObject;
  58633. };
  58634. // Parse serialized pipeline
  58635. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58636. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  58637. };
  58638. __decorate([
  58639. BABYLON.serialize()
  58640. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  58641. __decorate([
  58642. BABYLON.serialize()
  58643. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  58644. __decorate([
  58645. BABYLON.serialize()
  58646. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  58647. __decorate([
  58648. BABYLON.serialize()
  58649. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  58650. __decorate([
  58651. BABYLON.serialize()
  58652. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  58653. __decorate([
  58654. BABYLON.serialize()
  58655. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  58656. __decorate([
  58657. BABYLON.serialize()
  58658. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  58659. __decorate([
  58660. BABYLON.serialize()
  58661. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  58662. return DefaultRenderingPipeline;
  58663. }(BABYLON.PostProcessRenderPipeline));
  58664. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  58665. })(BABYLON || (BABYLON = {}));
  58666. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  58667. var BABYLON;
  58668. (function (BABYLON) {
  58669. var GeometryBufferRenderer = /** @class */ (function () {
  58670. function GeometryBufferRenderer(scene, ratio) {
  58671. if (ratio === void 0) { ratio = 1; }
  58672. this._enablePosition = false;
  58673. this._scene = scene;
  58674. this._ratio = ratio;
  58675. // Render target
  58676. this._createRenderTargets();
  58677. }
  58678. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  58679. set: function (meshes) {
  58680. this._multiRenderTarget.renderList = meshes;
  58681. },
  58682. enumerable: true,
  58683. configurable: true
  58684. });
  58685. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  58686. get: function () {
  58687. return this._multiRenderTarget.isSupported;
  58688. },
  58689. enumerable: true,
  58690. configurable: true
  58691. });
  58692. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  58693. get: function () {
  58694. return this._enablePosition;
  58695. },
  58696. set: function (enable) {
  58697. this._enablePosition = enable;
  58698. this.dispose();
  58699. this._createRenderTargets();
  58700. },
  58701. enumerable: true,
  58702. configurable: true
  58703. });
  58704. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  58705. var material = subMesh.getMaterial();
  58706. if (material && material.disableDepthWrite) {
  58707. return false;
  58708. }
  58709. var defines = [];
  58710. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  58711. var mesh = subMesh.getMesh();
  58712. // Alpha test
  58713. if (material && material.needAlphaTesting()) {
  58714. defines.push("#define ALPHATEST");
  58715. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58716. attribs.push(BABYLON.VertexBuffer.UVKind);
  58717. defines.push("#define UV1");
  58718. }
  58719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58720. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58721. defines.push("#define UV2");
  58722. }
  58723. }
  58724. // Buffers
  58725. if (this._enablePosition) {
  58726. defines.push("#define POSITION");
  58727. }
  58728. // Bones
  58729. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58730. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58731. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58732. if (mesh.numBoneInfluencers > 4) {
  58733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58735. }
  58736. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58737. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58738. }
  58739. else {
  58740. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58741. }
  58742. // Instances
  58743. if (useInstances) {
  58744. defines.push("#define INSTANCES");
  58745. attribs.push("world0");
  58746. attribs.push("world1");
  58747. attribs.push("world2");
  58748. attribs.push("world3");
  58749. }
  58750. // Get correct effect
  58751. var join = defines.join("\n");
  58752. if (this._cachedDefines !== join) {
  58753. this._cachedDefines = join;
  58754. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  58755. }
  58756. return this._effect.isReady();
  58757. };
  58758. GeometryBufferRenderer.prototype.getGBuffer = function () {
  58759. return this._multiRenderTarget;
  58760. };
  58761. // Methods
  58762. GeometryBufferRenderer.prototype.dispose = function () {
  58763. this.getGBuffer().dispose();
  58764. };
  58765. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  58766. var _this = this;
  58767. var engine = this._scene.getEngine();
  58768. var count = this._enablePosition ? 3 : 2;
  58769. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  58770. if (!this.isSupported) {
  58771. return;
  58772. }
  58773. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58774. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58775. this._multiRenderTarget.refreshRate = 1;
  58776. this._multiRenderTarget.renderParticles = false;
  58777. this._multiRenderTarget.renderList = null;
  58778. // set default depth value to 1.0 (far away)
  58779. this._multiRenderTarget.onClearObservable.add(function (engine) {
  58780. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  58781. });
  58782. // Custom render function
  58783. var renderSubMesh = function (subMesh) {
  58784. var mesh = subMesh.getRenderingMesh();
  58785. var scene = _this._scene;
  58786. var engine = scene.getEngine();
  58787. var material = subMesh.getMaterial();
  58788. if (!material) {
  58789. return;
  58790. }
  58791. // Culling
  58792. engine.setState(material.backFaceCulling);
  58793. // Managing instances
  58794. var batch = mesh._getInstancesRenderList(subMesh._id);
  58795. if (batch.mustReturn) {
  58796. return;
  58797. }
  58798. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58799. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  58800. engine.enableEffect(_this._effect);
  58801. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58802. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58803. _this._effect.setMatrix("view", scene.getViewMatrix());
  58804. // Alpha test
  58805. if (material && material.needAlphaTesting()) {
  58806. var alphaTexture = material.getAlphaTestTexture();
  58807. if (alphaTexture) {
  58808. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58809. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58810. }
  58811. }
  58812. // Bones
  58813. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58814. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58815. }
  58816. // Draw
  58817. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58818. }
  58819. };
  58820. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58821. var index;
  58822. if (depthOnlySubMeshes.length) {
  58823. engine.setColorWrite(false);
  58824. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58825. renderSubMesh(depthOnlySubMeshes.data[index]);
  58826. }
  58827. engine.setColorWrite(true);
  58828. }
  58829. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58830. renderSubMesh(opaqueSubMeshes.data[index]);
  58831. }
  58832. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58833. renderSubMesh(alphaTestSubMeshes.data[index]);
  58834. }
  58835. };
  58836. };
  58837. return GeometryBufferRenderer;
  58838. }());
  58839. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  58840. })(BABYLON || (BABYLON = {}));
  58841. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  58842. var BABYLON;
  58843. (function (BABYLON) {
  58844. var RefractionPostProcess = /** @class */ (function (_super) {
  58845. __extends(RefractionPostProcess, _super);
  58846. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  58847. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  58848. _this.color = color;
  58849. _this.depth = depth;
  58850. _this.colorLevel = colorLevel;
  58851. _this.onActivateObservable.add(function (cam) {
  58852. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  58853. });
  58854. _this.onApplyObservable.add(function (effect) {
  58855. effect.setColor3("baseColor", _this.color);
  58856. effect.setFloat("depth", _this.depth);
  58857. effect.setFloat("colorLevel", _this.colorLevel);
  58858. effect.setTexture("refractionSampler", _this._refRexture);
  58859. });
  58860. return _this;
  58861. }
  58862. // Methods
  58863. RefractionPostProcess.prototype.dispose = function (camera) {
  58864. if (this._refRexture) {
  58865. this._refRexture.dispose();
  58866. }
  58867. _super.prototype.dispose.call(this, camera);
  58868. };
  58869. return RefractionPostProcess;
  58870. }(BABYLON.PostProcess));
  58871. BABYLON.RefractionPostProcess = RefractionPostProcess;
  58872. })(BABYLON || (BABYLON = {}));
  58873. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  58874. var BABYLON;
  58875. (function (BABYLON) {
  58876. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  58877. __extends(BlackAndWhitePostProcess, _super);
  58878. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  58879. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  58880. _this.degree = 1;
  58881. _this.onApplyObservable.add(function (effect) {
  58882. effect.setFloat("degree", _this.degree);
  58883. });
  58884. return _this;
  58885. }
  58886. return BlackAndWhitePostProcess;
  58887. }(BABYLON.PostProcess));
  58888. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  58889. })(BABYLON || (BABYLON = {}));
  58890. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  58891. var BABYLON;
  58892. (function (BABYLON) {
  58893. var ConvolutionPostProcess = /** @class */ (function (_super) {
  58894. __extends(ConvolutionPostProcess, _super);
  58895. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  58896. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  58897. _this.kernel = kernel;
  58898. _this.onApply = function (effect) {
  58899. effect.setFloat2("screenSize", _this.width, _this.height);
  58900. effect.setArray("kernel", _this.kernel);
  58901. };
  58902. return _this;
  58903. }
  58904. // Statics
  58905. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  58906. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  58907. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  58908. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  58909. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  58910. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  58911. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  58912. return ConvolutionPostProcess;
  58913. }(BABYLON.PostProcess));
  58914. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  58915. })(BABYLON || (BABYLON = {}));
  58916. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  58917. var BABYLON;
  58918. (function (BABYLON) {
  58919. var FilterPostProcess = /** @class */ (function (_super) {
  58920. __extends(FilterPostProcess, _super);
  58921. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  58922. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  58923. _this.kernelMatrix = kernelMatrix;
  58924. _this.onApply = function (effect) {
  58925. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  58926. };
  58927. return _this;
  58928. }
  58929. return FilterPostProcess;
  58930. }(BABYLON.PostProcess));
  58931. BABYLON.FilterPostProcess = FilterPostProcess;
  58932. })(BABYLON || (BABYLON = {}));
  58933. //# sourceMappingURL=babylon.filterPostProcess.js.map
  58934. var BABYLON;
  58935. (function (BABYLON) {
  58936. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  58937. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  58938. __extends(VolumetricLightScatteringPostProcess, _super);
  58939. /**
  58940. * @constructor
  58941. * @param {string} name - The post-process name
  58942. * @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)
  58943. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  58944. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  58945. * @param {number} samples - The post-process quality, default 100
  58946. * @param {number} samplingMode - The post-process filtering mode
  58947. * @param {BABYLON.Engine} engine - The babylon engine
  58948. * @param {boolean} reusable - If the post-process is reusable
  58949. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  58950. */
  58951. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  58952. if (samples === void 0) { samples = 100; }
  58953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58954. 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;
  58955. _this._screenCoordinates = BABYLON.Vector2.Zero();
  58956. /**
  58957. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  58958. * @type {Vector3}
  58959. */
  58960. _this.customMeshPosition = BABYLON.Vector3.Zero();
  58961. /**
  58962. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  58963. * @type {boolean}
  58964. */
  58965. _this.useCustomMeshPosition = false;
  58966. /**
  58967. * If the post-process should inverse the light scattering direction
  58968. * @type {boolean}
  58969. */
  58970. _this.invert = true;
  58971. /**
  58972. * Array containing the excluded meshes not rendered in the internal pass
  58973. */
  58974. _this.excludedMeshes = new Array();
  58975. /**
  58976. * Controls the overall intensity of the post-process
  58977. * @type {number}
  58978. */
  58979. _this.exposure = 0.3;
  58980. /**
  58981. * Dissipates each sample's contribution in range [0, 1]
  58982. * @type {number}
  58983. */
  58984. _this.decay = 0.96815;
  58985. /**
  58986. * Controls the overall intensity of each sample
  58987. * @type {number}
  58988. */
  58989. _this.weight = 0.58767;
  58990. /**
  58991. * Controls the density of each sample
  58992. * @type {number}
  58993. */
  58994. _this.density = 0.926;
  58995. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  58996. engine = scene.getEngine();
  58997. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  58998. // Configure mesh
  58999. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59000. // Configure
  59001. _this._createPass(scene, ratio.passRatio || ratio);
  59002. _this.onActivate = function (camera) {
  59003. if (!_this.isSupported) {
  59004. _this.dispose(camera);
  59005. }
  59006. _this.onActivate = null;
  59007. };
  59008. _this.onApplyObservable.add(function (effect) {
  59009. _this._updateMeshScreenCoordinates(scene);
  59010. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59011. effect.setFloat("exposure", _this.exposure);
  59012. effect.setFloat("decay", _this.decay);
  59013. effect.setFloat("weight", _this.weight);
  59014. effect.setFloat("density", _this.density);
  59015. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59016. });
  59017. return _this;
  59018. }
  59019. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59020. get: function () {
  59021. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59022. return false;
  59023. },
  59024. set: function (useDiffuseColor) {
  59025. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59026. },
  59027. enumerable: true,
  59028. configurable: true
  59029. });
  59030. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59031. return "VolumetricLightScatteringPostProcess";
  59032. };
  59033. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59034. var mesh = subMesh.getMesh();
  59035. // Render this.mesh as default
  59036. if (mesh === this.mesh && mesh.material) {
  59037. return mesh.material.isReady(mesh);
  59038. }
  59039. var defines = [];
  59040. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59041. var material = subMesh.getMaterial();
  59042. // Alpha test
  59043. if (material) {
  59044. if (material.needAlphaTesting()) {
  59045. defines.push("#define ALPHATEST");
  59046. }
  59047. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59048. attribs.push(BABYLON.VertexBuffer.UVKind);
  59049. defines.push("#define UV1");
  59050. }
  59051. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59052. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59053. defines.push("#define UV2");
  59054. }
  59055. }
  59056. // Bones
  59057. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59058. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59059. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59060. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59061. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59062. }
  59063. else {
  59064. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59065. }
  59066. // Instances
  59067. if (useInstances) {
  59068. defines.push("#define INSTANCES");
  59069. attribs.push("world0");
  59070. attribs.push("world1");
  59071. attribs.push("world2");
  59072. attribs.push("world3");
  59073. }
  59074. // Get correct effect
  59075. var join = defines.join("\n");
  59076. if (this._cachedDefines !== join) {
  59077. this._cachedDefines = join;
  59078. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59079. }
  59080. return this._volumetricLightScatteringPass.isReady();
  59081. };
  59082. /**
  59083. * Sets the new light position for light scattering effect
  59084. * @param {BABYLON.Vector3} The new custom light position
  59085. */
  59086. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59087. this.customMeshPosition = position;
  59088. };
  59089. /**
  59090. * Returns the light position for light scattering effect
  59091. * @return {BABYLON.Vector3} The custom light position
  59092. */
  59093. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59094. return this.customMeshPosition;
  59095. };
  59096. /**
  59097. * Disposes the internal assets and detaches the post-process from the camera
  59098. */
  59099. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59100. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59101. if (rttIndex !== -1) {
  59102. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59103. }
  59104. this._volumetricLightScatteringRTT.dispose();
  59105. _super.prototype.dispose.call(this, camera);
  59106. };
  59107. /**
  59108. * Returns the render target texture used by the post-process
  59109. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59110. */
  59111. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59112. return this._volumetricLightScatteringRTT;
  59113. };
  59114. // Private methods
  59115. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59116. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59117. return true;
  59118. }
  59119. return false;
  59120. };
  59121. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59122. var _this = this;
  59123. var engine = scene.getEngine();
  59124. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59125. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59126. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59127. this._volumetricLightScatteringRTT.renderList = null;
  59128. this._volumetricLightScatteringRTT.renderParticles = false;
  59129. var camera = this.getCamera();
  59130. if (camera) {
  59131. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59132. }
  59133. else {
  59134. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59135. }
  59136. // Custom render function for submeshes
  59137. var renderSubMesh = function (subMesh) {
  59138. var mesh = subMesh.getRenderingMesh();
  59139. if (_this._meshExcluded(mesh)) {
  59140. return;
  59141. }
  59142. var material = subMesh.getMaterial();
  59143. if (!material) {
  59144. return;
  59145. }
  59146. var scene = mesh.getScene();
  59147. var engine = scene.getEngine();
  59148. // Culling
  59149. engine.setState(material.backFaceCulling);
  59150. // Managing instances
  59151. var batch = mesh._getInstancesRenderList(subMesh._id);
  59152. if (batch.mustReturn) {
  59153. return;
  59154. }
  59155. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59156. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59157. var effect = _this._volumetricLightScatteringPass;
  59158. if (mesh === _this.mesh) {
  59159. if (subMesh.effect) {
  59160. effect = subMesh.effect;
  59161. }
  59162. else {
  59163. effect = material.getEffect();
  59164. }
  59165. }
  59166. engine.enableEffect(effect);
  59167. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59168. if (mesh === _this.mesh) {
  59169. material.bind(mesh.getWorldMatrix(), mesh);
  59170. }
  59171. else {
  59172. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59173. // Alpha test
  59174. if (material && material.needAlphaTesting()) {
  59175. var alphaTexture = material.getAlphaTestTexture();
  59176. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59177. if (alphaTexture) {
  59178. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59179. }
  59180. }
  59181. // Bones
  59182. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59183. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59184. }
  59185. }
  59186. // Draw
  59187. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59188. }
  59189. };
  59190. // Render target texture callbacks
  59191. var savedSceneClearColor;
  59192. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59193. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59194. savedSceneClearColor = scene.clearColor;
  59195. scene.clearColor = sceneClearColor;
  59196. });
  59197. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59198. scene.clearColor = savedSceneClearColor;
  59199. });
  59200. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59201. var engine = scene.getEngine();
  59202. var index;
  59203. if (depthOnlySubMeshes.length) {
  59204. engine.setColorWrite(false);
  59205. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59206. renderSubMesh(depthOnlySubMeshes.data[index]);
  59207. }
  59208. engine.setColorWrite(true);
  59209. }
  59210. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59211. renderSubMesh(opaqueSubMeshes.data[index]);
  59212. }
  59213. engine.setAlphaTesting(true);
  59214. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59215. renderSubMesh(alphaTestSubMeshes.data[index]);
  59216. }
  59217. engine.setAlphaTesting(false);
  59218. if (transparentSubMeshes.length) {
  59219. // Sort sub meshes
  59220. for (index = 0; index < transparentSubMeshes.length; index++) {
  59221. var submesh = transparentSubMeshes.data[index];
  59222. var boundingInfo = submesh.getBoundingInfo();
  59223. if (boundingInfo && scene.activeCamera) {
  59224. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59225. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59226. }
  59227. }
  59228. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59229. sortedArray.sort(function (a, b) {
  59230. // Alpha index first
  59231. if (a._alphaIndex > b._alphaIndex) {
  59232. return 1;
  59233. }
  59234. if (a._alphaIndex < b._alphaIndex) {
  59235. return -1;
  59236. }
  59237. // Then distance to camera
  59238. if (a._distanceToCamera < b._distanceToCamera) {
  59239. return 1;
  59240. }
  59241. if (a._distanceToCamera > b._distanceToCamera) {
  59242. return -1;
  59243. }
  59244. return 0;
  59245. });
  59246. // Render sub meshes
  59247. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59248. for (index = 0; index < sortedArray.length; index++) {
  59249. renderSubMesh(sortedArray[index]);
  59250. }
  59251. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59252. }
  59253. };
  59254. };
  59255. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59256. var transform = scene.getTransformMatrix();
  59257. var meshPosition;
  59258. if (this.useCustomMeshPosition) {
  59259. meshPosition = this.customMeshPosition;
  59260. }
  59261. else if (this.attachedNode) {
  59262. meshPosition = this.attachedNode.position;
  59263. }
  59264. else {
  59265. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59266. }
  59267. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59268. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59269. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59270. if (this.invert)
  59271. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59272. };
  59273. // Static methods
  59274. /**
  59275. * Creates a default mesh for the Volumeric Light Scattering post-process
  59276. * @param {string} The mesh name
  59277. * @param {BABYLON.Scene} The scene where to create the mesh
  59278. * @return {BABYLON.Mesh} the default mesh
  59279. */
  59280. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59281. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59282. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59283. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59284. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59285. mesh.material = material;
  59286. return mesh;
  59287. };
  59288. __decorate([
  59289. BABYLON.serializeAsVector3()
  59290. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59291. __decorate([
  59292. BABYLON.serialize()
  59293. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59294. __decorate([
  59295. BABYLON.serialize()
  59296. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59297. __decorate([
  59298. BABYLON.serializeAsMeshReference()
  59299. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59300. __decorate([
  59301. BABYLON.serialize()
  59302. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59303. __decorate([
  59304. BABYLON.serialize()
  59305. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59306. __decorate([
  59307. BABYLON.serialize()
  59308. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59309. __decorate([
  59310. BABYLON.serialize()
  59311. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59312. __decorate([
  59313. BABYLON.serialize()
  59314. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59315. return VolumetricLightScatteringPostProcess;
  59316. }(BABYLON.PostProcess));
  59317. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59318. })(BABYLON || (BABYLON = {}));
  59319. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59320. //
  59321. // This post-process allows the modification of rendered colors by using
  59322. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59323. //
  59324. // The object needs to be provided an url to a texture containing the color
  59325. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59326. // Use an image editing software to tweak the LUT to match your needs.
  59327. //
  59328. // For an example of a color LUT, see here:
  59329. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59330. // For explanations on color grading, see here:
  59331. // http://udn.epicgames.com/Three/ColorGrading.html
  59332. //
  59333. var BABYLON;
  59334. (function (BABYLON) {
  59335. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59336. __extends(ColorCorrectionPostProcess, _super);
  59337. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59338. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59339. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59340. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59341. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59342. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59343. _this.onApply = function (effect) {
  59344. effect.setTexture("colorTable", _this._colorTableTexture);
  59345. };
  59346. return _this;
  59347. }
  59348. return ColorCorrectionPostProcess;
  59349. }(BABYLON.PostProcess));
  59350. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59351. })(BABYLON || (BABYLON = {}));
  59352. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59353. var BABYLON;
  59354. (function (BABYLON) {
  59355. var TonemappingOperator;
  59356. (function (TonemappingOperator) {
  59357. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59358. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59359. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59360. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59361. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59362. ;
  59363. var TonemapPostProcess = /** @class */ (function (_super) {
  59364. __extends(TonemapPostProcess, _super);
  59365. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59367. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59368. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59369. _this._operator = _operator;
  59370. _this.exposureAdjustment = exposureAdjustment;
  59371. var defines = "#define ";
  59372. if (_this._operator === TonemappingOperator.Hable)
  59373. defines += "HABLE_TONEMAPPING";
  59374. else if (_this._operator === TonemappingOperator.Reinhard)
  59375. defines += "REINHARD_TONEMAPPING";
  59376. else if (_this._operator === TonemappingOperator.HejiDawson)
  59377. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59378. else if (_this._operator === TonemappingOperator.Photographic)
  59379. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59380. //sadly a second call to create the effect.
  59381. _this.updateEffect(defines);
  59382. _this.onApply = function (effect) {
  59383. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59384. };
  59385. return _this;
  59386. }
  59387. return TonemapPostProcess;
  59388. }(BABYLON.PostProcess));
  59389. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59390. })(BABYLON || (BABYLON = {}));
  59391. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59392. var BABYLON;
  59393. (function (BABYLON) {
  59394. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59395. __extends(DisplayPassPostProcess, _super);
  59396. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59397. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59398. }
  59399. return DisplayPassPostProcess;
  59400. }(BABYLON.PostProcess));
  59401. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59402. })(BABYLON || (BABYLON = {}));
  59403. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59404. var BABYLON;
  59405. (function (BABYLON) {
  59406. var HighlightsPostProcess = /** @class */ (function (_super) {
  59407. __extends(HighlightsPostProcess, _super);
  59408. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59409. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59410. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59411. }
  59412. return HighlightsPostProcess;
  59413. }(BABYLON.PostProcess));
  59414. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59415. })(BABYLON || (BABYLON = {}));
  59416. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59417. var BABYLON;
  59418. (function (BABYLON) {
  59419. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59420. __extends(ImageProcessingPostProcess, _super);
  59421. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59422. if (camera === void 0) { camera = null; }
  59423. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59424. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59425. _this._fromLinearSpace = true;
  59426. /**
  59427. * Defines cache preventing GC.
  59428. */
  59429. _this._defines = {
  59430. IMAGEPROCESSING: false,
  59431. VIGNETTE: false,
  59432. VIGNETTEBLENDMODEMULTIPLY: false,
  59433. VIGNETTEBLENDMODEOPAQUE: false,
  59434. TONEMAPPING: false,
  59435. CONTRAST: false,
  59436. COLORCURVES: false,
  59437. COLORGRADING: false,
  59438. COLORGRADING3D: false,
  59439. FROMLINEARSPACE: false,
  59440. SAMPLER3DGREENDEPTH: false,
  59441. SAMPLER3DBGRMAP: false,
  59442. IMAGEPROCESSINGPOSTPROCESS: false,
  59443. EXPOSURE: false,
  59444. };
  59445. // Setup the default processing configuration to the scene.
  59446. _this._attachImageProcessingConfiguration(null, true);
  59447. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59448. _this.onApply = function (effect) {
  59449. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59450. };
  59451. return _this;
  59452. }
  59453. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59454. /**
  59455. * Gets the image processing configuration used either in this material.
  59456. */
  59457. get: function () {
  59458. return this._imageProcessingConfiguration;
  59459. },
  59460. /**
  59461. * Sets the Default image processing configuration used either in the this material.
  59462. *
  59463. * If sets to null, the scene one is in use.
  59464. */
  59465. set: function (value) {
  59466. this._attachImageProcessingConfiguration(value);
  59467. },
  59468. enumerable: true,
  59469. configurable: true
  59470. });
  59471. /**
  59472. * Attaches a new image processing configuration to the PBR Material.
  59473. * @param configuration
  59474. */
  59475. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59476. var _this = this;
  59477. if (doNotBuild === void 0) { doNotBuild = false; }
  59478. if (configuration === this._imageProcessingConfiguration) {
  59479. return;
  59480. }
  59481. // Detaches observer.
  59482. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59483. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59484. }
  59485. // Pick the scene configuration if needed.
  59486. if (!configuration) {
  59487. var scene = null;
  59488. var engine = this.getEngine();
  59489. var camera = this.getCamera();
  59490. if (camera) {
  59491. scene = camera.getScene();
  59492. }
  59493. else if (engine && engine.scenes) {
  59494. var scenes = engine.scenes;
  59495. scene = scenes[scenes.length - 1];
  59496. }
  59497. else {
  59498. scene = BABYLON.Engine.LastCreatedScene;
  59499. }
  59500. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59501. }
  59502. else {
  59503. this._imageProcessingConfiguration = configuration;
  59504. }
  59505. // Attaches observer.
  59506. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59507. _this._updateParameters();
  59508. });
  59509. // Ensure the effect will be rebuilt.
  59510. if (!doNotBuild) {
  59511. this._updateParameters();
  59512. }
  59513. };
  59514. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  59515. /**
  59516. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59517. */
  59518. get: function () {
  59519. return this.imageProcessingConfiguration.colorCurves;
  59520. },
  59521. /**
  59522. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59523. */
  59524. set: function (value) {
  59525. this.imageProcessingConfiguration.colorCurves = value;
  59526. },
  59527. enumerable: true,
  59528. configurable: true
  59529. });
  59530. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  59531. /**
  59532. * Gets wether the color curves effect is enabled.
  59533. */
  59534. get: function () {
  59535. return this.imageProcessingConfiguration.colorCurvesEnabled;
  59536. },
  59537. /**
  59538. * Sets wether the color curves effect is enabled.
  59539. */
  59540. set: function (value) {
  59541. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  59542. },
  59543. enumerable: true,
  59544. configurable: true
  59545. });
  59546. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  59547. /**
  59548. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59549. */
  59550. get: function () {
  59551. return this.imageProcessingConfiguration.colorGradingTexture;
  59552. },
  59553. /**
  59554. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59555. */
  59556. set: function (value) {
  59557. this.imageProcessingConfiguration.colorGradingTexture = value;
  59558. },
  59559. enumerable: true,
  59560. configurable: true
  59561. });
  59562. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  59563. /**
  59564. * Gets wether the color grading effect is enabled.
  59565. */
  59566. get: function () {
  59567. return this.imageProcessingConfiguration.colorGradingEnabled;
  59568. },
  59569. /**
  59570. * Gets wether the color grading effect is enabled.
  59571. */
  59572. set: function (value) {
  59573. this.imageProcessingConfiguration.colorGradingEnabled = value;
  59574. },
  59575. enumerable: true,
  59576. configurable: true
  59577. });
  59578. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  59579. /**
  59580. * Gets exposure used in the effect.
  59581. */
  59582. get: function () {
  59583. return this.imageProcessingConfiguration.exposure;
  59584. },
  59585. /**
  59586. * Sets exposure used in the effect.
  59587. */
  59588. set: function (value) {
  59589. this.imageProcessingConfiguration.exposure = value;
  59590. },
  59591. enumerable: true,
  59592. configurable: true
  59593. });
  59594. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  59595. /**
  59596. * Gets wether tonemapping is enabled or not.
  59597. */
  59598. get: function () {
  59599. return this._imageProcessingConfiguration.toneMappingEnabled;
  59600. },
  59601. /**
  59602. * Sets wether tonemapping is enabled or not
  59603. */
  59604. set: function (value) {
  59605. this._imageProcessingConfiguration.toneMappingEnabled = value;
  59606. },
  59607. enumerable: true,
  59608. configurable: true
  59609. });
  59610. ;
  59611. ;
  59612. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  59613. /**
  59614. * Gets contrast used in the effect.
  59615. */
  59616. get: function () {
  59617. return this.imageProcessingConfiguration.contrast;
  59618. },
  59619. /**
  59620. * Sets contrast used in the effect.
  59621. */
  59622. set: function (value) {
  59623. this.imageProcessingConfiguration.contrast = value;
  59624. },
  59625. enumerable: true,
  59626. configurable: true
  59627. });
  59628. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  59629. /**
  59630. * Gets Vignette stretch size.
  59631. */
  59632. get: function () {
  59633. return this.imageProcessingConfiguration.vignetteStretch;
  59634. },
  59635. /**
  59636. * Sets Vignette stretch size.
  59637. */
  59638. set: function (value) {
  59639. this.imageProcessingConfiguration.vignetteStretch = value;
  59640. },
  59641. enumerable: true,
  59642. configurable: true
  59643. });
  59644. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  59645. /**
  59646. * Gets Vignette centre X Offset.
  59647. */
  59648. get: function () {
  59649. return this.imageProcessingConfiguration.vignetteCentreX;
  59650. },
  59651. /**
  59652. * Sets Vignette centre X Offset.
  59653. */
  59654. set: function (value) {
  59655. this.imageProcessingConfiguration.vignetteCentreX = value;
  59656. },
  59657. enumerable: true,
  59658. configurable: true
  59659. });
  59660. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  59661. /**
  59662. * Gets Vignette centre Y Offset.
  59663. */
  59664. get: function () {
  59665. return this.imageProcessingConfiguration.vignetteCentreY;
  59666. },
  59667. /**
  59668. * Sets Vignette centre Y Offset.
  59669. */
  59670. set: function (value) {
  59671. this.imageProcessingConfiguration.vignetteCentreY = value;
  59672. },
  59673. enumerable: true,
  59674. configurable: true
  59675. });
  59676. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  59677. /**
  59678. * Gets Vignette weight or intensity of the vignette effect.
  59679. */
  59680. get: function () {
  59681. return this.imageProcessingConfiguration.vignetteWeight;
  59682. },
  59683. /**
  59684. * Sets Vignette weight or intensity of the vignette effect.
  59685. */
  59686. set: function (value) {
  59687. this.imageProcessingConfiguration.vignetteWeight = value;
  59688. },
  59689. enumerable: true,
  59690. configurable: true
  59691. });
  59692. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  59693. /**
  59694. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59695. * if vignetteEnabled is set to true.
  59696. */
  59697. get: function () {
  59698. return this.imageProcessingConfiguration.vignetteColor;
  59699. },
  59700. /**
  59701. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59702. * if vignetteEnabled is set to true.
  59703. */
  59704. set: function (value) {
  59705. this.imageProcessingConfiguration.vignetteColor = value;
  59706. },
  59707. enumerable: true,
  59708. configurable: true
  59709. });
  59710. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  59711. /**
  59712. * Gets Camera field of view used by the Vignette effect.
  59713. */
  59714. get: function () {
  59715. return this.imageProcessingConfiguration.vignetteCameraFov;
  59716. },
  59717. /**
  59718. * Sets Camera field of view used by the Vignette effect.
  59719. */
  59720. set: function (value) {
  59721. this.imageProcessingConfiguration.vignetteCameraFov = value;
  59722. },
  59723. enumerable: true,
  59724. configurable: true
  59725. });
  59726. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  59727. /**
  59728. * Gets the vignette blend mode allowing different kind of effect.
  59729. */
  59730. get: function () {
  59731. return this.imageProcessingConfiguration.vignetteBlendMode;
  59732. },
  59733. /**
  59734. * Sets the vignette blend mode allowing different kind of effect.
  59735. */
  59736. set: function (value) {
  59737. this.imageProcessingConfiguration.vignetteBlendMode = value;
  59738. },
  59739. enumerable: true,
  59740. configurable: true
  59741. });
  59742. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  59743. /**
  59744. * Gets wether the vignette effect is enabled.
  59745. */
  59746. get: function () {
  59747. return this.imageProcessingConfiguration.vignetteEnabled;
  59748. },
  59749. /**
  59750. * Sets wether the vignette effect is enabled.
  59751. */
  59752. set: function (value) {
  59753. this.imageProcessingConfiguration.vignetteEnabled = value;
  59754. },
  59755. enumerable: true,
  59756. configurable: true
  59757. });
  59758. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  59759. /**
  59760. * Gets wether the input of the processing is in Gamma or Linear Space.
  59761. */
  59762. get: function () {
  59763. return this._fromLinearSpace;
  59764. },
  59765. /**
  59766. * Sets wether the input of the processing is in Gamma or Linear Space.
  59767. */
  59768. set: function (value) {
  59769. if (this._fromLinearSpace === value) {
  59770. return;
  59771. }
  59772. this._fromLinearSpace = value;
  59773. this._updateParameters();
  59774. },
  59775. enumerable: true,
  59776. configurable: true
  59777. });
  59778. ImageProcessingPostProcess.prototype.getClassName = function () {
  59779. return "ImageProcessingPostProcess";
  59780. };
  59781. ImageProcessingPostProcess.prototype._updateParameters = function () {
  59782. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  59783. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  59784. var defines = "";
  59785. for (var define in this._defines) {
  59786. if (this._defines[define]) {
  59787. defines += "#define " + define + ";\r\n";
  59788. }
  59789. }
  59790. var samplers = ["textureSampler"];
  59791. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  59792. var uniforms = ["scale"];
  59793. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  59794. this.updateEffect(defines, uniforms, samplers);
  59795. };
  59796. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  59797. _super.prototype.dispose.call(this, camera);
  59798. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59799. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59800. }
  59801. this.imageProcessingConfiguration.applyByPostProcess = false;
  59802. };
  59803. __decorate([
  59804. BABYLON.serialize()
  59805. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  59806. return ImageProcessingPostProcess;
  59807. }(BABYLON.PostProcess));
  59808. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  59809. })(BABYLON || (BABYLON = {}));
  59810. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  59811. var BABYLON;
  59812. (function (BABYLON) {
  59813. var BlurPostProcess = /** @class */ (function (_super) {
  59814. __extends(BlurPostProcess, _super);
  59815. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  59816. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59817. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59818. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  59819. _this.direction = direction;
  59820. _this._packedFloat = false;
  59821. _this.onApplyObservable.add(function (effect) {
  59822. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  59823. });
  59824. _this.kernel = kernel;
  59825. return _this;
  59826. }
  59827. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  59828. /**
  59829. * Gets the length in pixels of the blur sample region
  59830. */
  59831. get: function () {
  59832. return this._idealKernel;
  59833. },
  59834. /**
  59835. * Sets the length in pixels of the blur sample region
  59836. */
  59837. set: function (v) {
  59838. if (this._idealKernel === v) {
  59839. return;
  59840. }
  59841. v = Math.max(v, 1);
  59842. this._idealKernel = v;
  59843. this._kernel = this._nearestBestKernel(v);
  59844. this._updateParameters();
  59845. },
  59846. enumerable: true,
  59847. configurable: true
  59848. });
  59849. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  59850. /**
  59851. * Gets wether or not the blur is unpacking/repacking floats
  59852. */
  59853. get: function () {
  59854. return this._packedFloat;
  59855. },
  59856. /**
  59857. * Sets wether or not the blur needs to unpack/repack floats
  59858. */
  59859. set: function (v) {
  59860. if (this._packedFloat === v) {
  59861. return;
  59862. }
  59863. this._packedFloat = v;
  59864. this._updateParameters();
  59865. },
  59866. enumerable: true,
  59867. configurable: true
  59868. });
  59869. BlurPostProcess.prototype._updateParameters = function () {
  59870. // Generate sampling offsets and weights
  59871. var N = this._kernel;
  59872. var centerIndex = (N - 1) / 2;
  59873. // Generate Gaussian sampling weights over kernel
  59874. var offsets = [];
  59875. var weights = [];
  59876. var totalWeight = 0;
  59877. for (var i = 0; i < N; i++) {
  59878. var u = i / (N - 1);
  59879. var w = this._gaussianWeight(u * 2.0 - 1);
  59880. offsets[i] = (i - centerIndex);
  59881. weights[i] = w;
  59882. totalWeight += w;
  59883. }
  59884. // Normalize weights
  59885. for (var i = 0; i < weights.length; i++) {
  59886. weights[i] /= totalWeight;
  59887. }
  59888. // Optimize: combine samples to take advantage of hardware linear sampling
  59889. // Walk from left to center, combining pairs (symmetrically)
  59890. var linearSamplingWeights = [];
  59891. var linearSamplingOffsets = [];
  59892. var linearSamplingMap = [];
  59893. for (var i = 0; i <= centerIndex; i += 2) {
  59894. var j = Math.min(i + 1, Math.floor(centerIndex));
  59895. var singleCenterSample = i === j;
  59896. if (singleCenterSample) {
  59897. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  59898. }
  59899. else {
  59900. var sharedCell = j === centerIndex;
  59901. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  59902. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  59903. if (offsetLinear === 0) {
  59904. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  59905. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  59906. }
  59907. else {
  59908. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  59909. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  59910. }
  59911. }
  59912. }
  59913. for (var i = 0; i < linearSamplingMap.length; i++) {
  59914. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  59915. linearSamplingWeights[i] = linearSamplingMap[i].w;
  59916. }
  59917. // Replace with optimized
  59918. offsets = linearSamplingOffsets;
  59919. weights = linearSamplingWeights;
  59920. // Generate shaders
  59921. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  59922. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  59923. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  59924. var defines = "";
  59925. for (var i = 0; i < varyingCount; i++) {
  59926. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  59927. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  59928. }
  59929. var depCount = 0;
  59930. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  59931. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  59932. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  59933. depCount++;
  59934. }
  59935. if (this.packedFloat) {
  59936. defines += "#define PACKEDFLOAT 1";
  59937. }
  59938. this.updateEffect(defines, null, null, {
  59939. varyingCount: varyingCount,
  59940. depCount: depCount
  59941. });
  59942. };
  59943. /**
  59944. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  59945. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  59946. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  59947. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  59948. * The gaps between physical kernels are compensated for in the weighting of the samples
  59949. * @param idealKernel Ideal blur kernel.
  59950. * @return Nearest best kernel.
  59951. */
  59952. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  59953. var v = Math.round(idealKernel);
  59954. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  59955. var k = _a[_i];
  59956. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  59957. return Math.max(k, 3);
  59958. }
  59959. }
  59960. return Math.max(v, 3);
  59961. };
  59962. /**
  59963. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  59964. * @param x The point on the Gaussian distribution to sample.
  59965. * @return the value of the Gaussian function at x.
  59966. */
  59967. BlurPostProcess.prototype._gaussianWeight = function (x) {
  59968. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  59969. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  59970. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  59971. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  59972. // truncated at around 1.3% of peak strength.
  59973. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  59974. var sigma = (1 / 3);
  59975. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  59976. var exponent = -((x * x) / (2.0 * sigma * sigma));
  59977. var weight = (1.0 / denominator) * Math.exp(exponent);
  59978. return weight;
  59979. };
  59980. /**
  59981. * Generates a string that can be used as a floating point number in GLSL.
  59982. * @param x Value to print.
  59983. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  59984. * @return GLSL float string.
  59985. */
  59986. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  59987. if (decimalFigures === void 0) { decimalFigures = 8; }
  59988. return x.toFixed(decimalFigures).replace(/0+$/, '');
  59989. };
  59990. return BlurPostProcess;
  59991. }(BABYLON.PostProcess));
  59992. BABYLON.BlurPostProcess = BlurPostProcess;
  59993. })(BABYLON || (BABYLON = {}));
  59994. //# sourceMappingURL=babylon.blurPostProcess.js.map
  59995. /// <reference path="..\babylon.node.ts" />
  59996. var BABYLON;
  59997. (function (BABYLON) {
  59998. var Bone = /** @class */ (function (_super) {
  59999. __extends(Bone, _super);
  60000. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60001. if (parentBone === void 0) { parentBone = null; }
  60002. if (localMatrix === void 0) { localMatrix = null; }
  60003. if (restPose === void 0) { restPose = null; }
  60004. if (baseMatrix === void 0) { baseMatrix = null; }
  60005. if (index === void 0) { index = null; }
  60006. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60007. _this.name = name;
  60008. _this.children = new Array();
  60009. _this.animations = new Array();
  60010. // Set this value to map this bone to a different index in the transform matrices.
  60011. // Set this value to -1 to exclude the bone from the transform matrices.
  60012. _this._index = null;
  60013. _this._worldTransform = new BABYLON.Matrix();
  60014. _this._absoluteTransform = new BABYLON.Matrix();
  60015. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60016. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60017. _this._scaleVector = BABYLON.Vector3.One();
  60018. _this._negateScaleChildren = BABYLON.Vector3.One();
  60019. _this._scalingDeterminant = 1;
  60020. _this._skeleton = skeleton;
  60021. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60022. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60023. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60024. _this._index = index;
  60025. skeleton.bones.push(_this);
  60026. _this.setParent(parentBone, false);
  60027. _this._updateDifferenceMatrix();
  60028. return _this;
  60029. }
  60030. Object.defineProperty(Bone.prototype, "_matrix", {
  60031. get: function () {
  60032. return this._localMatrix;
  60033. },
  60034. set: function (val) {
  60035. if (this._localMatrix) {
  60036. this._localMatrix.copyFrom(val);
  60037. }
  60038. else {
  60039. this._localMatrix = val;
  60040. }
  60041. },
  60042. enumerable: true,
  60043. configurable: true
  60044. });
  60045. // Members
  60046. Bone.prototype.getSkeleton = function () {
  60047. return this._skeleton;
  60048. };
  60049. Bone.prototype.getParent = function () {
  60050. return this._parent;
  60051. };
  60052. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60053. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60054. if (this._parent === parent) {
  60055. return;
  60056. }
  60057. if (this._parent) {
  60058. var index = this._parent.children.indexOf(this);
  60059. if (index !== -1) {
  60060. this._parent.children.splice(index, 1);
  60061. }
  60062. }
  60063. this._parent = parent;
  60064. if (this._parent) {
  60065. this._parent.children.push(this);
  60066. }
  60067. if (updateDifferenceMatrix) {
  60068. this._updateDifferenceMatrix();
  60069. }
  60070. };
  60071. Bone.prototype.getLocalMatrix = function () {
  60072. return this._localMatrix;
  60073. };
  60074. Bone.prototype.getBaseMatrix = function () {
  60075. return this._baseMatrix;
  60076. };
  60077. Bone.prototype.getRestPose = function () {
  60078. return this._restPose;
  60079. };
  60080. Bone.prototype.returnToRest = function () {
  60081. this.updateMatrix(this._restPose.clone());
  60082. };
  60083. Bone.prototype.getWorldMatrix = function () {
  60084. return this._worldTransform;
  60085. };
  60086. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60087. return this._invertedAbsoluteTransform;
  60088. };
  60089. Bone.prototype.getAbsoluteTransform = function () {
  60090. return this._absoluteTransform;
  60091. };
  60092. Object.defineProperty(Bone.prototype, "position", {
  60093. // Properties (matches AbstractMesh properties)
  60094. get: function () {
  60095. return this.getPosition();
  60096. },
  60097. set: function (newPosition) {
  60098. this.setPosition(newPosition);
  60099. },
  60100. enumerable: true,
  60101. configurable: true
  60102. });
  60103. Object.defineProperty(Bone.prototype, "rotation", {
  60104. get: function () {
  60105. return this.getRotation();
  60106. },
  60107. set: function (newRotation) {
  60108. this.setRotation(newRotation);
  60109. },
  60110. enumerable: true,
  60111. configurable: true
  60112. });
  60113. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60114. get: function () {
  60115. return this.getRotationQuaternion();
  60116. },
  60117. set: function (newRotation) {
  60118. this.setRotationQuaternion(newRotation);
  60119. },
  60120. enumerable: true,
  60121. configurable: true
  60122. });
  60123. Object.defineProperty(Bone.prototype, "scaling", {
  60124. get: function () {
  60125. return this.getScale();
  60126. },
  60127. set: function (newScaling) {
  60128. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60129. },
  60130. enumerable: true,
  60131. configurable: true
  60132. });
  60133. // Methods
  60134. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60135. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60136. this._baseMatrix = matrix.clone();
  60137. this._localMatrix = matrix.clone();
  60138. this._skeleton._markAsDirty();
  60139. if (updateDifferenceMatrix) {
  60140. this._updateDifferenceMatrix();
  60141. }
  60142. };
  60143. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60144. if (!rootMatrix) {
  60145. rootMatrix = this._baseMatrix;
  60146. }
  60147. if (this._parent) {
  60148. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60149. }
  60150. else {
  60151. this._absoluteTransform.copyFrom(rootMatrix);
  60152. }
  60153. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60154. for (var index = 0; index < this.children.length; index++) {
  60155. this.children[index]._updateDifferenceMatrix();
  60156. }
  60157. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60158. };
  60159. Bone.prototype.markAsDirty = function () {
  60160. this._currentRenderId++;
  60161. this._skeleton._markAsDirty();
  60162. };
  60163. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60164. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60165. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60166. // all animation may be coming from a library skeleton, so may need to create animation
  60167. if (this.animations.length === 0) {
  60168. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60169. this.animations[0].setKeys([]);
  60170. }
  60171. // get animation info / verify there is such a range from the source bone
  60172. var sourceRange = source.animations[0].getRange(rangeName);
  60173. if (!sourceRange) {
  60174. return false;
  60175. }
  60176. var from = sourceRange.from;
  60177. var to = sourceRange.to;
  60178. var sourceKeys = source.animations[0].getKeys();
  60179. // rescaling prep
  60180. var sourceBoneLength = source.length;
  60181. var sourceParent = source.getParent();
  60182. var parent = this.getParent();
  60183. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60184. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60185. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60186. var destKeys = this.animations[0].getKeys();
  60187. // loop vars declaration
  60188. var orig;
  60189. var origTranslation;
  60190. var mat;
  60191. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60192. orig = sourceKeys[key];
  60193. if (orig.frame >= from && orig.frame <= to) {
  60194. if (rescaleAsRequired) {
  60195. mat = orig.value.clone();
  60196. // scale based on parent ratio, when bone has parent
  60197. if (parentScalingReqd) {
  60198. origTranslation = mat.getTranslation();
  60199. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60200. // scale based on skeleton dimension ratio when root bone, and value is passed
  60201. }
  60202. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60203. origTranslation = mat.getTranslation();
  60204. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60205. // use original when root bone, and no data for skelDimensionsRatio
  60206. }
  60207. else {
  60208. mat = orig.value;
  60209. }
  60210. }
  60211. else {
  60212. mat = orig.value;
  60213. }
  60214. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60215. }
  60216. }
  60217. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60218. return true;
  60219. };
  60220. /**
  60221. * Translate the bone in local or world space.
  60222. * @param vec The amount to translate the bone.
  60223. * @param space The space that the translation is in.
  60224. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60225. */
  60226. Bone.prototype.translate = function (vec, space, mesh) {
  60227. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60228. var lm = this.getLocalMatrix();
  60229. if (space == BABYLON.Space.LOCAL) {
  60230. lm.m[12] += vec.x;
  60231. lm.m[13] += vec.y;
  60232. lm.m[14] += vec.z;
  60233. }
  60234. else {
  60235. var wm = null;
  60236. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60237. if (mesh) {
  60238. wm = mesh.getWorldMatrix();
  60239. }
  60240. this._skeleton.computeAbsoluteTransforms();
  60241. var tmat = Bone._tmpMats[0];
  60242. var tvec = Bone._tmpVecs[0];
  60243. if (this._parent) {
  60244. if (mesh && wm) {
  60245. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60246. tmat.multiplyToRef(wm, tmat);
  60247. }
  60248. else {
  60249. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60250. }
  60251. }
  60252. tmat.m[12] = 0;
  60253. tmat.m[13] = 0;
  60254. tmat.m[14] = 0;
  60255. tmat.invert();
  60256. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60257. lm.m[12] += tvec.x;
  60258. lm.m[13] += tvec.y;
  60259. lm.m[14] += tvec.z;
  60260. }
  60261. this.markAsDirty();
  60262. };
  60263. /**
  60264. * Set the postion of the bone in local or world space.
  60265. * @param position The position to set the bone.
  60266. * @param space The space that the position is in.
  60267. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60268. */
  60269. Bone.prototype.setPosition = function (position, space, mesh) {
  60270. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60271. var lm = this.getLocalMatrix();
  60272. if (space == BABYLON.Space.LOCAL) {
  60273. lm.m[12] = position.x;
  60274. lm.m[13] = position.y;
  60275. lm.m[14] = position.z;
  60276. }
  60277. else {
  60278. var wm = null;
  60279. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60280. if (mesh) {
  60281. wm = mesh.getWorldMatrix();
  60282. }
  60283. this._skeleton.computeAbsoluteTransforms();
  60284. var tmat = Bone._tmpMats[0];
  60285. var vec = Bone._tmpVecs[0];
  60286. if (this._parent) {
  60287. if (mesh && wm) {
  60288. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60289. tmat.multiplyToRef(wm, tmat);
  60290. }
  60291. else {
  60292. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60293. }
  60294. }
  60295. tmat.invert();
  60296. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60297. lm.m[12] = vec.x;
  60298. lm.m[13] = vec.y;
  60299. lm.m[14] = vec.z;
  60300. }
  60301. this.markAsDirty();
  60302. };
  60303. /**
  60304. * Set the absolute postion of the bone (world space).
  60305. * @param position The position to set the bone.
  60306. * @param mesh The mesh that this bone is attached to.
  60307. */
  60308. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60309. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60310. };
  60311. /**
  60312. * Set the scale of the bone on the x, y and z axes.
  60313. * @param x The scale of the bone on the x axis.
  60314. * @param x The scale of the bone on the y axis.
  60315. * @param z The scale of the bone on the z axis.
  60316. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60317. */
  60318. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60319. if (scaleChildren === void 0) { scaleChildren = false; }
  60320. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60321. if (!scaleChildren) {
  60322. this._negateScaleChildren.x = 1 / x;
  60323. this._negateScaleChildren.y = 1 / y;
  60324. this._negateScaleChildren.z = 1 / z;
  60325. }
  60326. this._syncScaleVector();
  60327. }
  60328. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60329. };
  60330. /**
  60331. * Scale the bone on the x, y and z axes.
  60332. * @param x The amount to scale the bone on the x axis.
  60333. * @param x The amount to scale the bone on the y axis.
  60334. * @param z The amount to scale the bone on the z axis.
  60335. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60336. */
  60337. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60338. if (scaleChildren === void 0) { scaleChildren = false; }
  60339. var locMat = this.getLocalMatrix();
  60340. var origLocMat = Bone._tmpMats[0];
  60341. origLocMat.copyFrom(locMat);
  60342. var origLocMatInv = Bone._tmpMats[1];
  60343. origLocMatInv.copyFrom(origLocMat);
  60344. origLocMatInv.invert();
  60345. var scaleMat = Bone._tmpMats[2];
  60346. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60347. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60348. this._scaleVector.x *= x;
  60349. this._scaleVector.y *= y;
  60350. this._scaleVector.z *= z;
  60351. locMat.multiplyToRef(origLocMatInv, locMat);
  60352. locMat.multiplyToRef(scaleMat, locMat);
  60353. locMat.multiplyToRef(origLocMat, locMat);
  60354. var parent = this.getParent();
  60355. if (parent) {
  60356. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60357. }
  60358. else {
  60359. this.getAbsoluteTransform().copyFrom(locMat);
  60360. }
  60361. var len = this.children.length;
  60362. scaleMat.invert();
  60363. for (var i = 0; i < len; i++) {
  60364. var child = this.children[i];
  60365. var cm = child.getLocalMatrix();
  60366. cm.multiplyToRef(scaleMat, cm);
  60367. var lm = child.getLocalMatrix();
  60368. lm.m[12] *= x;
  60369. lm.m[13] *= y;
  60370. lm.m[14] *= z;
  60371. }
  60372. this.computeAbsoluteTransforms();
  60373. if (scaleChildren) {
  60374. for (var i = 0; i < len; i++) {
  60375. this.children[i].scale(x, y, z, scaleChildren);
  60376. }
  60377. }
  60378. this.markAsDirty();
  60379. };
  60380. /**
  60381. * Set the yaw, pitch, and roll of the bone in local or world space.
  60382. * @param yaw The rotation of the bone on the y axis.
  60383. * @param pitch The rotation of the bone on the x axis.
  60384. * @param roll The rotation of the bone on the z axis.
  60385. * @param space The space that the axes of rotation are in.
  60386. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60387. */
  60388. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60389. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60390. var rotMat = Bone._tmpMats[0];
  60391. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60392. var rotMatInv = Bone._tmpMats[1];
  60393. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60394. rotMatInv.multiplyToRef(rotMat, rotMat);
  60395. this._rotateWithMatrix(rotMat, space, mesh);
  60396. };
  60397. /**
  60398. * Rotate the bone on an axis in local or world space.
  60399. * @param axis The axis to rotate the bone on.
  60400. * @param amount The amount to rotate the bone.
  60401. * @param space The space that the axis is in.
  60402. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60403. */
  60404. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60405. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60406. var rmat = Bone._tmpMats[0];
  60407. rmat.m[12] = 0;
  60408. rmat.m[13] = 0;
  60409. rmat.m[14] = 0;
  60410. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60411. this._rotateWithMatrix(rmat, space, mesh);
  60412. };
  60413. /**
  60414. * Set the rotation of the bone to a particular axis angle in local or world space.
  60415. * @param axis The axis to rotate the bone on.
  60416. * @param angle The angle that the bone should be rotated to.
  60417. * @param space The space that the axis is in.
  60418. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60419. */
  60420. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60421. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60422. var rotMat = Bone._tmpMats[0];
  60423. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60424. var rotMatInv = Bone._tmpMats[1];
  60425. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60426. rotMatInv.multiplyToRef(rotMat, rotMat);
  60427. this._rotateWithMatrix(rotMat, space, mesh);
  60428. };
  60429. /**
  60430. * Set the euler rotation of the bone in local of world space.
  60431. * @param rotation The euler rotation that the bone should be set to.
  60432. * @param space The space that the rotation is in.
  60433. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60434. */
  60435. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60436. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60437. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60438. };
  60439. /**
  60440. * Set the quaternion rotation of the bone in local of world space.
  60441. * @param quat The quaternion rotation that the bone should be set to.
  60442. * @param space The space that the rotation is in.
  60443. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60444. */
  60445. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60447. var rotMatInv = Bone._tmpMats[0];
  60448. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60449. var rotMat = Bone._tmpMats[1];
  60450. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60451. rotMatInv.multiplyToRef(rotMat, rotMat);
  60452. this._rotateWithMatrix(rotMat, space, mesh);
  60453. };
  60454. /**
  60455. * Set the rotation matrix of the bone in local of world space.
  60456. * @param rotMat The rotation matrix that the bone should be set to.
  60457. * @param space The space that the rotation is in.
  60458. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60459. */
  60460. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60461. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60462. var rotMatInv = Bone._tmpMats[0];
  60463. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60464. var rotMat2 = Bone._tmpMats[1];
  60465. rotMat2.copyFrom(rotMat);
  60466. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60467. this._rotateWithMatrix(rotMat2, space, mesh);
  60468. };
  60469. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60471. var lmat = this.getLocalMatrix();
  60472. var lx = lmat.m[12];
  60473. var ly = lmat.m[13];
  60474. var lz = lmat.m[14];
  60475. var parent = this.getParent();
  60476. var parentScale = Bone._tmpMats[3];
  60477. var parentScaleInv = Bone._tmpMats[4];
  60478. if (parent) {
  60479. if (space == BABYLON.Space.WORLD) {
  60480. if (mesh) {
  60481. parentScale.copyFrom(mesh.getWorldMatrix());
  60482. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60483. }
  60484. else {
  60485. parentScale.copyFrom(parent.getAbsoluteTransform());
  60486. }
  60487. }
  60488. else {
  60489. parentScale = parent._scaleMatrix;
  60490. }
  60491. parentScaleInv.copyFrom(parentScale);
  60492. parentScaleInv.invert();
  60493. lmat.multiplyToRef(parentScale, lmat);
  60494. lmat.multiplyToRef(rmat, lmat);
  60495. lmat.multiplyToRef(parentScaleInv, lmat);
  60496. }
  60497. else {
  60498. if (space == BABYLON.Space.WORLD && mesh) {
  60499. parentScale.copyFrom(mesh.getWorldMatrix());
  60500. parentScaleInv.copyFrom(parentScale);
  60501. parentScaleInv.invert();
  60502. lmat.multiplyToRef(parentScale, lmat);
  60503. lmat.multiplyToRef(rmat, lmat);
  60504. lmat.multiplyToRef(parentScaleInv, lmat);
  60505. }
  60506. else {
  60507. lmat.multiplyToRef(rmat, lmat);
  60508. }
  60509. }
  60510. lmat.m[12] = lx;
  60511. lmat.m[13] = ly;
  60512. lmat.m[14] = lz;
  60513. this.computeAbsoluteTransforms();
  60514. this.markAsDirty();
  60515. };
  60516. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  60517. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60518. if (space == BABYLON.Space.WORLD) {
  60519. var scaleMatrix = Bone._tmpMats[2];
  60520. scaleMatrix.copyFrom(this._scaleMatrix);
  60521. rotMatInv.copyFrom(this.getAbsoluteTransform());
  60522. if (mesh) {
  60523. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  60524. var meshScale = Bone._tmpMats[3];
  60525. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  60526. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  60527. }
  60528. rotMatInv.invert();
  60529. scaleMatrix.m[0] *= this._scalingDeterminant;
  60530. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60531. }
  60532. else {
  60533. rotMatInv.copyFrom(this.getLocalMatrix());
  60534. rotMatInv.invert();
  60535. var scaleMatrix = Bone._tmpMats[2];
  60536. scaleMatrix.copyFrom(this._scaleMatrix);
  60537. if (this._parent) {
  60538. var pscaleMatrix = Bone._tmpMats[3];
  60539. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  60540. pscaleMatrix.invert();
  60541. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  60542. }
  60543. else {
  60544. scaleMatrix.m[0] *= this._scalingDeterminant;
  60545. }
  60546. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60547. }
  60548. };
  60549. /**
  60550. * Get the scale of the bone
  60551. * @returns the scale of the bone
  60552. */
  60553. Bone.prototype.getScale = function () {
  60554. return this._scaleVector.clone();
  60555. };
  60556. /**
  60557. * Copy the scale of the bone to a vector3.
  60558. * @param result The vector3 to copy the scale to
  60559. */
  60560. Bone.prototype.getScaleToRef = function (result) {
  60561. result.copyFrom(this._scaleVector);
  60562. };
  60563. /**
  60564. * Get the position of the bone in local or world space.
  60565. * @param space The space that the returned position is in.
  60566. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60567. * @returns The position of the bone
  60568. */
  60569. Bone.prototype.getPosition = function (space, mesh) {
  60570. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60571. if (mesh === void 0) { mesh = null; }
  60572. var pos = BABYLON.Vector3.Zero();
  60573. this.getPositionToRef(space, mesh, pos);
  60574. return pos;
  60575. };
  60576. /**
  60577. * Copy the position of the bone to a vector3 in local or world space.
  60578. * @param space The space that the returned position is in.
  60579. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60580. * @param result The vector3 to copy the position to.
  60581. */
  60582. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  60583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60584. if (space == BABYLON.Space.LOCAL) {
  60585. var lm = this.getLocalMatrix();
  60586. result.x = lm.m[12];
  60587. result.y = lm.m[13];
  60588. result.z = lm.m[14];
  60589. }
  60590. else {
  60591. var wm = null;
  60592. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60593. if (mesh) {
  60594. wm = mesh.getWorldMatrix();
  60595. }
  60596. this._skeleton.computeAbsoluteTransforms();
  60597. var tmat = Bone._tmpMats[0];
  60598. if (mesh && wm) {
  60599. tmat.copyFrom(this.getAbsoluteTransform());
  60600. tmat.multiplyToRef(wm, tmat);
  60601. }
  60602. else {
  60603. tmat = this.getAbsoluteTransform();
  60604. }
  60605. result.x = tmat.m[12];
  60606. result.y = tmat.m[13];
  60607. result.z = tmat.m[14];
  60608. }
  60609. };
  60610. /**
  60611. * Get the absolute position of the bone (world space).
  60612. * @param mesh The mesh that this bone is attached to.
  60613. * @returns The absolute position of the bone
  60614. */
  60615. Bone.prototype.getAbsolutePosition = function (mesh) {
  60616. if (mesh === void 0) { mesh = null; }
  60617. var pos = BABYLON.Vector3.Zero();
  60618. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  60619. return pos;
  60620. };
  60621. /**
  60622. * Copy the absolute position of the bone (world space) to the result param.
  60623. * @param mesh The mesh that this bone is attached to.
  60624. * @param result The vector3 to copy the absolute position to.
  60625. */
  60626. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  60627. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  60628. };
  60629. /**
  60630. * Compute the absolute transforms of this bone and its children.
  60631. */
  60632. Bone.prototype.computeAbsoluteTransforms = function () {
  60633. if (this._parent) {
  60634. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60635. }
  60636. else {
  60637. this._absoluteTransform.copyFrom(this._localMatrix);
  60638. var poseMatrix = this._skeleton.getPoseMatrix();
  60639. if (poseMatrix) {
  60640. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  60641. }
  60642. }
  60643. var children = this.children;
  60644. var len = children.length;
  60645. for (var i = 0; i < len; i++) {
  60646. children[i].computeAbsoluteTransforms();
  60647. }
  60648. };
  60649. Bone.prototype._syncScaleVector = function () {
  60650. var lm = this.getLocalMatrix();
  60651. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  60652. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  60653. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  60654. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  60655. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  60656. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  60657. this._scaleVector.x = xs * Math.sqrt(xsq);
  60658. this._scaleVector.y = ys * Math.sqrt(ysq);
  60659. this._scaleVector.z = zs * Math.sqrt(zsq);
  60660. if (this._parent) {
  60661. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  60662. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  60663. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  60664. }
  60665. 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);
  60666. };
  60667. /**
  60668. * Get the world direction from an axis that is in the local space of the bone.
  60669. * @param localAxis The local direction that is used to compute the world direction.
  60670. * @param mesh The mesh that this bone is attached to.
  60671. * @returns The world direction
  60672. */
  60673. Bone.prototype.getDirection = function (localAxis, mesh) {
  60674. if (mesh === void 0) { mesh = null; }
  60675. var result = BABYLON.Vector3.Zero();
  60676. this.getDirectionToRef(localAxis, mesh, result);
  60677. return result;
  60678. };
  60679. /**
  60680. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  60681. * @param localAxis The local direction that is used to compute the world direction.
  60682. * @param mesh The mesh that this bone is attached to.
  60683. * @param result The vector3 that the world direction will be copied to.
  60684. */
  60685. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  60686. if (mesh === void 0) { mesh = null; }
  60687. var wm = null;
  60688. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60689. if (mesh) {
  60690. wm = mesh.getWorldMatrix();
  60691. }
  60692. this._skeleton.computeAbsoluteTransforms();
  60693. var mat = Bone._tmpMats[0];
  60694. mat.copyFrom(this.getAbsoluteTransform());
  60695. if (mesh && wm) {
  60696. mat.multiplyToRef(wm, mat);
  60697. }
  60698. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  60699. result.normalize();
  60700. };
  60701. /**
  60702. * Get the euler rotation of the bone in local or world space.
  60703. * @param space The space that the rotation should be in.
  60704. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60705. * @returns The euler rotation
  60706. */
  60707. Bone.prototype.getRotation = function (space, mesh) {
  60708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60709. if (mesh === void 0) { mesh = null; }
  60710. var result = BABYLON.Vector3.Zero();
  60711. this.getRotationToRef(space, mesh, result);
  60712. return result;
  60713. };
  60714. /**
  60715. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  60716. * @param space The space that the rotation should be in.
  60717. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60718. * @param result The vector3 that the rotation should be copied to.
  60719. */
  60720. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  60721. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60722. if (mesh === void 0) { mesh = null; }
  60723. var quat = Bone._tmpQuat;
  60724. this.getRotationQuaternionToRef(space, mesh, quat);
  60725. quat.toEulerAnglesToRef(result);
  60726. };
  60727. /**
  60728. * Get the quaternion rotation of the bone in either local or world space.
  60729. * @param space The space that the rotation should be in.
  60730. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60731. * @returns The quaternion rotation
  60732. */
  60733. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  60734. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60735. if (mesh === void 0) { mesh = null; }
  60736. var result = BABYLON.Quaternion.Identity();
  60737. this.getRotationQuaternionToRef(space, mesh, result);
  60738. return result;
  60739. };
  60740. /**
  60741. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  60742. * @param space The space that the rotation should be in.
  60743. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60744. * @param result The quaternion that the rotation should be copied to.
  60745. */
  60746. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  60747. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60748. if (mesh === void 0) { mesh = null; }
  60749. if (space == BABYLON.Space.LOCAL) {
  60750. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60751. }
  60752. else {
  60753. var mat = Bone._tmpMats[0];
  60754. var amat = this.getAbsoluteTransform();
  60755. if (mesh) {
  60756. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60757. }
  60758. else {
  60759. mat.copyFrom(amat);
  60760. }
  60761. mat.m[0] *= this._scalingDeterminant;
  60762. mat.m[1] *= this._scalingDeterminant;
  60763. mat.m[2] *= this._scalingDeterminant;
  60764. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60765. }
  60766. };
  60767. /**
  60768. * Get the rotation matrix of the bone in local or world space.
  60769. * @param space The space that the rotation should be in.
  60770. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60771. * @returns The rotation matrix
  60772. */
  60773. Bone.prototype.getRotationMatrix = function (space, mesh) {
  60774. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60775. var result = BABYLON.Matrix.Identity();
  60776. this.getRotationMatrixToRef(space, mesh, result);
  60777. return result;
  60778. };
  60779. /**
  60780. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  60781. * @param space The space that the rotation should be in.
  60782. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60783. * @param result The quaternion that the rotation should be copied to.
  60784. */
  60785. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  60786. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60787. if (space == BABYLON.Space.LOCAL) {
  60788. this.getLocalMatrix().getRotationMatrixToRef(result);
  60789. }
  60790. else {
  60791. var mat = Bone._tmpMats[0];
  60792. var amat = this.getAbsoluteTransform();
  60793. if (mesh) {
  60794. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60795. }
  60796. else {
  60797. mat.copyFrom(amat);
  60798. }
  60799. mat.m[0] *= this._scalingDeterminant;
  60800. mat.m[1] *= this._scalingDeterminant;
  60801. mat.m[2] *= this._scalingDeterminant;
  60802. mat.getRotationMatrixToRef(result);
  60803. }
  60804. };
  60805. /**
  60806. * Get the world position of a point that is in the local space of the bone.
  60807. * @param position The local position
  60808. * @param mesh The mesh that this bone is attached to.
  60809. * @returns The world position
  60810. */
  60811. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  60812. if (mesh === void 0) { mesh = null; }
  60813. var result = BABYLON.Vector3.Zero();
  60814. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  60815. return result;
  60816. };
  60817. /**
  60818. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  60819. * @param position The local position
  60820. * @param mesh The mesh that this bone is attached to.
  60821. * @param result The vector3 that the world position should be copied to.
  60822. */
  60823. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  60824. if (mesh === void 0) { mesh = null; }
  60825. var wm = null;
  60826. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60827. if (mesh) {
  60828. wm = mesh.getWorldMatrix();
  60829. }
  60830. this._skeleton.computeAbsoluteTransforms();
  60831. var tmat = Bone._tmpMats[0];
  60832. if (mesh && wm) {
  60833. tmat.copyFrom(this.getAbsoluteTransform());
  60834. tmat.multiplyToRef(wm, tmat);
  60835. }
  60836. else {
  60837. tmat = this.getAbsoluteTransform();
  60838. }
  60839. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  60840. };
  60841. /**
  60842. * Get the local position of a point that is in world space.
  60843. * @param position The world position
  60844. * @param mesh The mesh that this bone is attached to.
  60845. * @returns The local position
  60846. */
  60847. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  60848. if (mesh === void 0) { mesh = null; }
  60849. var result = BABYLON.Vector3.Zero();
  60850. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  60851. return result;
  60852. };
  60853. /**
  60854. * Get the local position of a point that is in world space and copy it to the result param.
  60855. * @param position The world position
  60856. * @param mesh The mesh that this bone is attached to.
  60857. * @param result The vector3 that the local position should be copied to.
  60858. */
  60859. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  60860. if (mesh === void 0) { mesh = null; }
  60861. var wm = null;
  60862. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60863. if (mesh) {
  60864. wm = mesh.getWorldMatrix();
  60865. }
  60866. this._skeleton.computeAbsoluteTransforms();
  60867. var tmat = Bone._tmpMats[0];
  60868. tmat.copyFrom(this.getAbsoluteTransform());
  60869. if (mesh && wm) {
  60870. tmat.multiplyToRef(wm, tmat);
  60871. }
  60872. tmat.invert();
  60873. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  60874. };
  60875. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60876. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  60877. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  60878. return Bone;
  60879. }(BABYLON.Node));
  60880. BABYLON.Bone = Bone;
  60881. })(BABYLON || (BABYLON = {}));
  60882. //# sourceMappingURL=babylon.bone.js.map
  60883. var BABYLON;
  60884. (function (BABYLON) {
  60885. var BoneIKController = /** @class */ (function () {
  60886. function BoneIKController(mesh, bone, options) {
  60887. this.targetPosition = BABYLON.Vector3.Zero();
  60888. this.poleTargetPosition = BABYLON.Vector3.Zero();
  60889. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  60890. this.poleAngle = 0;
  60891. this.slerpAmount = 1;
  60892. this._bone1Quat = BABYLON.Quaternion.Identity();
  60893. this._bone1Mat = BABYLON.Matrix.Identity();
  60894. this._bone2Ang = Math.PI;
  60895. this._maxAngle = Math.PI;
  60896. this._rightHandedSystem = false;
  60897. this._bendAxis = BABYLON.Vector3.Right();
  60898. this._slerping = false;
  60899. this._adjustRoll = 0;
  60900. this._bone2 = bone;
  60901. this._bone1 = bone.getParent();
  60902. if (!this._bone1) {
  60903. return;
  60904. }
  60905. this.mesh = mesh;
  60906. var bonePos = bone.getPosition();
  60907. if (bone.getAbsoluteTransform().determinant() > 0) {
  60908. this._rightHandedSystem = true;
  60909. this._bendAxis.x = 0;
  60910. this._bendAxis.y = 0;
  60911. this._bendAxis.z = -1;
  60912. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  60913. this._adjustRoll = Math.PI * .5;
  60914. this._bendAxis.z = 1;
  60915. }
  60916. }
  60917. if (this._bone1.length) {
  60918. var boneScale1 = this._bone1.getScale();
  60919. var boneScale2 = this._bone2.getScale();
  60920. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  60921. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  60922. }
  60923. else if (this._bone1.children[0]) {
  60924. mesh.computeWorldMatrix(true);
  60925. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  60926. var pos2 = this._bone2.getAbsolutePosition(mesh);
  60927. var pos3 = this._bone1.getAbsolutePosition(mesh);
  60928. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  60929. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  60930. }
  60931. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  60932. this.maxAngle = Math.PI;
  60933. if (options) {
  60934. if (options.targetMesh) {
  60935. this.targetMesh = options.targetMesh;
  60936. this.targetMesh.computeWorldMatrix(true);
  60937. }
  60938. if (options.poleTargetMesh) {
  60939. this.poleTargetMesh = options.poleTargetMesh;
  60940. this.poleTargetMesh.computeWorldMatrix(true);
  60941. }
  60942. else if (options.poleTargetBone) {
  60943. this.poleTargetBone = options.poleTargetBone;
  60944. }
  60945. else if (this._bone1.getParent()) {
  60946. this.poleTargetBone = this._bone1.getParent();
  60947. }
  60948. if (options.poleTargetLocalOffset) {
  60949. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  60950. }
  60951. if (options.poleAngle) {
  60952. this.poleAngle = options.poleAngle;
  60953. }
  60954. if (options.bendAxis) {
  60955. this._bendAxis.copyFrom(options.bendAxis);
  60956. }
  60957. if (options.maxAngle) {
  60958. this.maxAngle = options.maxAngle;
  60959. }
  60960. if (options.slerpAmount) {
  60961. this.slerpAmount = options.slerpAmount;
  60962. }
  60963. }
  60964. }
  60965. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  60966. get: function () {
  60967. return this._maxAngle;
  60968. },
  60969. set: function (value) {
  60970. this._setMaxAngle(value);
  60971. },
  60972. enumerable: true,
  60973. configurable: true
  60974. });
  60975. BoneIKController.prototype._setMaxAngle = function (ang) {
  60976. if (ang < 0) {
  60977. ang = 0;
  60978. }
  60979. if (ang > Math.PI || ang == undefined) {
  60980. ang = Math.PI;
  60981. }
  60982. this._maxAngle = ang;
  60983. var a = this._bone1Length;
  60984. var b = this._bone2Length;
  60985. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  60986. };
  60987. BoneIKController.prototype.update = function () {
  60988. var bone1 = this._bone1;
  60989. if (!bone1) {
  60990. return;
  60991. }
  60992. var target = this.targetPosition;
  60993. var poleTarget = this.poleTargetPosition;
  60994. var mat1 = BoneIKController._tmpMats[0];
  60995. var mat2 = BoneIKController._tmpMats[1];
  60996. if (this.targetMesh) {
  60997. target.copyFrom(this.targetMesh.getAbsolutePosition());
  60998. }
  60999. if (this.poleTargetBone) {
  61000. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61001. }
  61002. else if (this.poleTargetMesh) {
  61003. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61004. }
  61005. var bonePos = BoneIKController._tmpVecs[0];
  61006. var zaxis = BoneIKController._tmpVecs[1];
  61007. var xaxis = BoneIKController._tmpVecs[2];
  61008. var yaxis = BoneIKController._tmpVecs[3];
  61009. var upAxis = BoneIKController._tmpVecs[4];
  61010. var _tmpQuat = BoneIKController._tmpQuat;
  61011. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61012. poleTarget.subtractToRef(bonePos, upAxis);
  61013. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61014. upAxis.y = 1;
  61015. }
  61016. else {
  61017. upAxis.normalize();
  61018. }
  61019. target.subtractToRef(bonePos, yaxis);
  61020. yaxis.normalize();
  61021. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61022. zaxis.normalize();
  61023. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61024. xaxis.normalize();
  61025. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61026. var a = this._bone1Length;
  61027. var b = this._bone2Length;
  61028. var c = BABYLON.Vector3.Distance(bonePos, target);
  61029. if (this._maxReach > 0) {
  61030. c = Math.min(this._maxReach, c);
  61031. }
  61032. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61033. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61034. if (acosa > 1) {
  61035. acosa = 1;
  61036. }
  61037. if (acosb > 1) {
  61038. acosb = 1;
  61039. }
  61040. if (acosa < -1) {
  61041. acosa = -1;
  61042. }
  61043. if (acosb < -1) {
  61044. acosb = -1;
  61045. }
  61046. var angA = Math.acos(acosa);
  61047. var angB = Math.acos(acosb);
  61048. var angC = -angA - angB;
  61049. if (this._rightHandedSystem) {
  61050. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61051. mat2.multiplyToRef(mat1, mat1);
  61052. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61053. mat2.multiplyToRef(mat1, mat1);
  61054. }
  61055. else {
  61056. var _tmpVec = BoneIKController._tmpVecs[5];
  61057. _tmpVec.copyFrom(this._bendAxis);
  61058. _tmpVec.x *= -1;
  61059. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61060. mat2.multiplyToRef(mat1, mat1);
  61061. }
  61062. if (this.poleAngle) {
  61063. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61064. mat1.multiplyToRef(mat2, mat1);
  61065. }
  61066. if (this._bone1) {
  61067. if (this.slerpAmount < 1) {
  61068. if (!this._slerping) {
  61069. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61070. }
  61071. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61072. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61073. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61074. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61075. this._slerping = true;
  61076. }
  61077. else {
  61078. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61079. this._bone1Mat.copyFrom(mat1);
  61080. this._slerping = false;
  61081. }
  61082. }
  61083. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61084. this._bone2Ang = angC;
  61085. };
  61086. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61087. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61088. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61089. return BoneIKController;
  61090. }());
  61091. BABYLON.BoneIKController = BoneIKController;
  61092. })(BABYLON || (BABYLON = {}));
  61093. //# sourceMappingURL=babylon.boneIKController.js.map
  61094. var BABYLON;
  61095. (function (BABYLON) {
  61096. var BoneLookController = /** @class */ (function () {
  61097. /**
  61098. * Create a BoneLookController
  61099. * @param mesh the mesh that the bone belongs to
  61100. * @param bone the bone that will be looking to the target
  61101. * @param target the target Vector3 to look at
  61102. * @param settings optional settings:
  61103. * - maxYaw: the maximum angle the bone will yaw to
  61104. * - minYaw: the minimum angle the bone will yaw to
  61105. * - maxPitch: the maximum angle the bone will pitch to
  61106. * - minPitch: the minimum angle the bone will yaw to
  61107. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61108. * - upAxis: the up axis of the coordinate system
  61109. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61110. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61111. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61112. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61113. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61114. * - adjustRoll: used to make an adjustment to the roll of the bone
  61115. **/
  61116. function BoneLookController(mesh, bone, target, options) {
  61117. /**
  61118. * The up axis of the coordinate system that is used when the bone is rotated.
  61119. */
  61120. this.upAxis = BABYLON.Vector3.Up();
  61121. /**
  61122. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61123. */
  61124. this.upAxisSpace = BABYLON.Space.LOCAL;
  61125. /**
  61126. * Used to make an adjustment to the yaw of the bone.
  61127. */
  61128. this.adjustYaw = 0;
  61129. /**
  61130. * Used to make an adjustment to the pitch of the bone.
  61131. */
  61132. this.adjustPitch = 0;
  61133. /**
  61134. * Used to make an adjustment to the roll of the bone.
  61135. */
  61136. this.adjustRoll = 0;
  61137. /**
  61138. * 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).
  61139. */
  61140. this.slerpAmount = 1;
  61141. this._boneQuat = BABYLON.Quaternion.Identity();
  61142. this._slerping = false;
  61143. this._firstFrameSkipped = false;
  61144. this._fowardAxis = BABYLON.Vector3.Forward();
  61145. this.mesh = mesh;
  61146. this.bone = bone;
  61147. this.target = target;
  61148. if (options) {
  61149. if (options.adjustYaw) {
  61150. this.adjustYaw = options.adjustYaw;
  61151. }
  61152. if (options.adjustPitch) {
  61153. this.adjustPitch = options.adjustPitch;
  61154. }
  61155. if (options.adjustRoll) {
  61156. this.adjustRoll = options.adjustRoll;
  61157. }
  61158. if (options.maxYaw != null) {
  61159. this.maxYaw = options.maxYaw;
  61160. }
  61161. else {
  61162. this.maxYaw = Math.PI;
  61163. }
  61164. if (options.minYaw != null) {
  61165. this.minYaw = options.minYaw;
  61166. }
  61167. else {
  61168. this.minYaw = -Math.PI;
  61169. }
  61170. if (options.maxPitch != null) {
  61171. this.maxPitch = options.maxPitch;
  61172. }
  61173. else {
  61174. this.maxPitch = Math.PI;
  61175. }
  61176. if (options.minPitch != null) {
  61177. this.minPitch = options.minPitch;
  61178. }
  61179. else {
  61180. this.minPitch = -Math.PI;
  61181. }
  61182. if (options.slerpAmount != null) {
  61183. this.slerpAmount = options.slerpAmount;
  61184. }
  61185. if (options.upAxis != null) {
  61186. this.upAxis = options.upAxis;
  61187. }
  61188. if (options.upAxisSpace != null) {
  61189. this.upAxisSpace = options.upAxisSpace;
  61190. }
  61191. if (options.yawAxis != null || options.pitchAxis != null) {
  61192. var newYawAxis = BABYLON.Axis.Y;
  61193. var newPitchAxis = BABYLON.Axis.X;
  61194. if (options.yawAxis != null) {
  61195. newYawAxis = options.yawAxis.clone();
  61196. newYawAxis.normalize();
  61197. }
  61198. if (options.pitchAxis != null) {
  61199. newPitchAxis = options.pitchAxis.clone();
  61200. newPitchAxis.normalize();
  61201. }
  61202. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61203. this._transformYawPitch = BABYLON.Matrix.Identity();
  61204. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61205. this._transformYawPitchInv = this._transformYawPitch.clone();
  61206. this._transformYawPitch.invert();
  61207. }
  61208. }
  61209. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61210. this.upAxisSpace = BABYLON.Space.LOCAL;
  61211. }
  61212. }
  61213. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61214. /**
  61215. * Get/set the minimum yaw angle that the bone can look to.
  61216. */
  61217. get: function () {
  61218. return this._minYaw;
  61219. },
  61220. set: function (value) {
  61221. this._minYaw = value;
  61222. this._minYawSin = Math.sin(value);
  61223. this._minYawCos = Math.cos(value);
  61224. if (this._maxYaw != null) {
  61225. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61226. this._yawRange = this._maxYaw - this._minYaw;
  61227. }
  61228. },
  61229. enumerable: true,
  61230. configurable: true
  61231. });
  61232. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61233. /**
  61234. * Get/set the maximum yaw angle that the bone can look to.
  61235. */
  61236. get: function () {
  61237. return this._maxYaw;
  61238. },
  61239. set: function (value) {
  61240. this._maxYaw = value;
  61241. this._maxYawSin = Math.sin(value);
  61242. this._maxYawCos = Math.cos(value);
  61243. if (this._minYaw != null) {
  61244. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61245. this._yawRange = this._maxYaw - this._minYaw;
  61246. }
  61247. },
  61248. enumerable: true,
  61249. configurable: true
  61250. });
  61251. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61252. /**
  61253. * Get/set the minimum pitch angle that the bone can look to.
  61254. */
  61255. get: function () {
  61256. return this._minPitch;
  61257. },
  61258. set: function (value) {
  61259. this._minPitch = value;
  61260. this._minPitchTan = Math.tan(value);
  61261. },
  61262. enumerable: true,
  61263. configurable: true
  61264. });
  61265. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61266. /**
  61267. * Get/set the maximum pitch angle that the bone can look to.
  61268. */
  61269. get: function () {
  61270. return this._maxPitch;
  61271. },
  61272. set: function (value) {
  61273. this._maxPitch = value;
  61274. this._maxPitchTan = Math.tan(value);
  61275. },
  61276. enumerable: true,
  61277. configurable: true
  61278. });
  61279. /**
  61280. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61281. */
  61282. BoneLookController.prototype.update = function () {
  61283. //skip the first frame when slerping so that the mesh rotation is correct
  61284. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61285. this._firstFrameSkipped = true;
  61286. return;
  61287. }
  61288. var bone = this.bone;
  61289. var bonePos = BoneLookController._tmpVecs[0];
  61290. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61291. var target = this.target;
  61292. var _tmpMat1 = BoneLookController._tmpMats[0];
  61293. var _tmpMat2 = BoneLookController._tmpMats[1];
  61294. var mesh = this.mesh;
  61295. var parentBone = bone.getParent();
  61296. var upAxis = BoneLookController._tmpVecs[1];
  61297. upAxis.copyFrom(this.upAxis);
  61298. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61299. if (this._transformYawPitch) {
  61300. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61301. }
  61302. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61303. }
  61304. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61305. mesh.getDirectionToRef(upAxis, upAxis);
  61306. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61307. upAxis.normalize();
  61308. }
  61309. }
  61310. var checkYaw = false;
  61311. var checkPitch = false;
  61312. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61313. checkYaw = true;
  61314. }
  61315. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61316. checkPitch = true;
  61317. }
  61318. if (checkYaw || checkPitch) {
  61319. var spaceMat = BoneLookController._tmpMats[2];
  61320. var spaceMatInv = BoneLookController._tmpMats[3];
  61321. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61322. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61323. }
  61324. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61325. spaceMat.copyFrom(mesh.getWorldMatrix());
  61326. }
  61327. else {
  61328. var forwardAxis = BoneLookController._tmpVecs[2];
  61329. forwardAxis.copyFrom(this._fowardAxis);
  61330. if (this._transformYawPitch) {
  61331. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61332. }
  61333. if (parentBone) {
  61334. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61335. }
  61336. else {
  61337. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61338. }
  61339. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61340. rightAxis.normalize();
  61341. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61342. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61343. }
  61344. spaceMat.invertToRef(spaceMatInv);
  61345. var xzlen = null;
  61346. if (checkPitch) {
  61347. var localTarget = BoneLookController._tmpVecs[3];
  61348. target.subtractToRef(bonePos, localTarget);
  61349. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61350. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61351. var pitch = Math.atan2(localTarget.y, xzlen);
  61352. var newPitch = pitch;
  61353. if (pitch > this._maxPitch) {
  61354. localTarget.y = this._maxPitchTan * xzlen;
  61355. newPitch = this._maxPitch;
  61356. }
  61357. else if (pitch < this._minPitch) {
  61358. localTarget.y = this._minPitchTan * xzlen;
  61359. newPitch = this._minPitch;
  61360. }
  61361. if (pitch != newPitch) {
  61362. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61363. localTarget.addInPlace(bonePos);
  61364. target = localTarget;
  61365. }
  61366. }
  61367. if (checkYaw) {
  61368. var localTarget = BoneLookController._tmpVecs[4];
  61369. target.subtractToRef(bonePos, localTarget);
  61370. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61371. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61372. var newYaw = yaw;
  61373. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61374. if (xzlen == null) {
  61375. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61376. }
  61377. if (this._yawRange > Math.PI) {
  61378. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61379. localTarget.z = this._maxYawCos * xzlen;
  61380. localTarget.x = this._maxYawSin * xzlen;
  61381. newYaw = this._maxYaw;
  61382. }
  61383. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61384. localTarget.z = this._minYawCos * xzlen;
  61385. localTarget.x = this._minYawSin * xzlen;
  61386. newYaw = this._minYaw;
  61387. }
  61388. }
  61389. else {
  61390. if (yaw > this._maxYaw) {
  61391. localTarget.z = this._maxYawCos * xzlen;
  61392. localTarget.x = this._maxYawSin * xzlen;
  61393. newYaw = this._maxYaw;
  61394. }
  61395. else if (yaw < this._minYaw) {
  61396. localTarget.z = this._minYawCos * xzlen;
  61397. localTarget.x = this._minYawSin * xzlen;
  61398. newYaw = this._minYaw;
  61399. }
  61400. }
  61401. }
  61402. if (this._slerping && this._yawRange > Math.PI) {
  61403. //are we going to be crossing into the min/max region?
  61404. var boneFwd = BoneLookController._tmpVecs[8];
  61405. boneFwd.copyFrom(BABYLON.Axis.Z);
  61406. if (this._transformYawPitch) {
  61407. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61408. }
  61409. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61410. this._boneQuat.toRotationMatrix(boneRotMat);
  61411. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61412. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61413. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61414. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61415. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61416. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61417. if (angBtwTar > angBtwMidYaw) {
  61418. if (xzlen == null) {
  61419. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61420. }
  61421. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61422. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61423. if (angBtwMin < angBtwMax) {
  61424. newYaw = boneYaw + Math.PI * .75;
  61425. localTarget.z = Math.cos(newYaw) * xzlen;
  61426. localTarget.x = Math.sin(newYaw) * xzlen;
  61427. }
  61428. else {
  61429. newYaw = boneYaw - Math.PI * .75;
  61430. localTarget.z = Math.cos(newYaw) * xzlen;
  61431. localTarget.x = Math.sin(newYaw) * xzlen;
  61432. }
  61433. }
  61434. }
  61435. if (yaw != newYaw) {
  61436. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61437. localTarget.addInPlace(bonePos);
  61438. target = localTarget;
  61439. }
  61440. }
  61441. }
  61442. var zaxis = BoneLookController._tmpVecs[5];
  61443. var xaxis = BoneLookController._tmpVecs[6];
  61444. var yaxis = BoneLookController._tmpVecs[7];
  61445. var _tmpQuat = BoneLookController._tmpQuat;
  61446. target.subtractToRef(bonePos, zaxis);
  61447. zaxis.normalize();
  61448. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61449. xaxis.normalize();
  61450. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61451. yaxis.normalize();
  61452. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61453. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61454. return;
  61455. }
  61456. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61457. return;
  61458. }
  61459. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61460. return;
  61461. }
  61462. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61463. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61464. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61465. }
  61466. if (this.slerpAmount < 1) {
  61467. if (!this._slerping) {
  61468. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61469. }
  61470. if (this._transformYawPitch) {
  61471. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61472. }
  61473. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61474. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61475. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61476. this._slerping = true;
  61477. }
  61478. else {
  61479. if (this._transformYawPitch) {
  61480. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61481. }
  61482. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61483. this._slerping = false;
  61484. }
  61485. };
  61486. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61487. var angDiff = ang2 - ang1;
  61488. angDiff %= Math.PI * 2;
  61489. if (angDiff > Math.PI) {
  61490. angDiff -= Math.PI * 2;
  61491. }
  61492. else if (angDiff < -Math.PI) {
  61493. angDiff += Math.PI * 2;
  61494. }
  61495. return angDiff;
  61496. };
  61497. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61498. ang1 %= (2 * Math.PI);
  61499. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61500. ang2 %= (2 * Math.PI);
  61501. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61502. var ab = 0;
  61503. if (ang1 < ang2) {
  61504. ab = ang2 - ang1;
  61505. }
  61506. else {
  61507. ab = ang1 - ang2;
  61508. }
  61509. if (ab > Math.PI) {
  61510. ab = Math.PI * 2 - ab;
  61511. }
  61512. return ab;
  61513. };
  61514. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  61515. ang %= (2 * Math.PI);
  61516. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  61517. ang1 %= (2 * Math.PI);
  61518. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61519. ang2 %= (2 * Math.PI);
  61520. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61521. if (ang1 < ang2) {
  61522. if (ang > ang1 && ang < ang2) {
  61523. return true;
  61524. }
  61525. }
  61526. else {
  61527. if (ang > ang2 && ang < ang1) {
  61528. return true;
  61529. }
  61530. }
  61531. return false;
  61532. };
  61533. 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()];
  61534. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  61535. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61536. return BoneLookController;
  61537. }());
  61538. BABYLON.BoneLookController = BoneLookController;
  61539. })(BABYLON || (BABYLON = {}));
  61540. //# sourceMappingURL=babylon.boneLookController.js.map
  61541. var BABYLON;
  61542. (function (BABYLON) {
  61543. var Skeleton = /** @class */ (function () {
  61544. function Skeleton(name, id, scene) {
  61545. this.name = name;
  61546. this.id = id;
  61547. this.bones = new Array();
  61548. this.needInitialSkinMatrix = false;
  61549. this._isDirty = true;
  61550. this._meshesWithPoseMatrix = new Array();
  61551. this._identity = BABYLON.Matrix.Identity();
  61552. this._ranges = {};
  61553. this._lastAbsoluteTransformsUpdateId = -1;
  61554. // Events
  61555. /**
  61556. * An event triggered before computing the skeleton's matrices
  61557. * @type {BABYLON.Observable}
  61558. */
  61559. this.onBeforeComputeObservable = new BABYLON.Observable();
  61560. this.bones = [];
  61561. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61562. scene.skeletons.push(this);
  61563. //make sure it will recalculate the matrix next time prepare is called.
  61564. this._isDirty = true;
  61565. }
  61566. // Members
  61567. Skeleton.prototype.getTransformMatrices = function (mesh) {
  61568. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  61569. return mesh._bonesTransformMatrices;
  61570. }
  61571. if (!this._transformMatrices) {
  61572. this.prepare();
  61573. }
  61574. return this._transformMatrices;
  61575. };
  61576. Skeleton.prototype.getScene = function () {
  61577. return this._scene;
  61578. };
  61579. // Methods
  61580. /**
  61581. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  61582. */
  61583. Skeleton.prototype.toString = function (fullDetails) {
  61584. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  61585. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  61586. if (fullDetails) {
  61587. ret += ", Ranges: {";
  61588. var first = true;
  61589. for (var name_1 in this._ranges) {
  61590. if (first) {
  61591. ret += ", ";
  61592. first = false;
  61593. }
  61594. ret += name_1;
  61595. }
  61596. ret += "}";
  61597. }
  61598. return ret;
  61599. };
  61600. /**
  61601. * Get bone's index searching by name
  61602. * @param {string} name is bone's name to search for
  61603. * @return {number} Indice of the bone. Returns -1 if not found
  61604. */
  61605. Skeleton.prototype.getBoneIndexByName = function (name) {
  61606. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  61607. if (this.bones[boneIndex].name === name) {
  61608. return boneIndex;
  61609. }
  61610. }
  61611. return -1;
  61612. };
  61613. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  61614. // check name not already in use
  61615. if (!this._ranges[name]) {
  61616. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  61617. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61618. if (this.bones[i].animations[0]) {
  61619. this.bones[i].animations[0].createRange(name, from, to);
  61620. }
  61621. }
  61622. }
  61623. };
  61624. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  61625. if (deleteFrames === void 0) { deleteFrames = true; }
  61626. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61627. if (this.bones[i].animations[0]) {
  61628. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  61629. }
  61630. }
  61631. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  61632. };
  61633. Skeleton.prototype.getAnimationRange = function (name) {
  61634. return this._ranges[name];
  61635. };
  61636. /**
  61637. * Returns as an Array, all AnimationRanges defined on this skeleton
  61638. */
  61639. Skeleton.prototype.getAnimationRanges = function () {
  61640. var animationRanges = [];
  61641. var name;
  61642. var i = 0;
  61643. for (name in this._ranges) {
  61644. animationRanges[i] = this._ranges[name];
  61645. i++;
  61646. }
  61647. return animationRanges;
  61648. };
  61649. /**
  61650. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  61651. */
  61652. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  61653. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61654. if (this._ranges[name] || !source.getAnimationRange(name)) {
  61655. return false;
  61656. }
  61657. var ret = true;
  61658. var frameOffset = this._getHighestAnimationFrame() + 1;
  61659. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  61660. var boneDict = {};
  61661. var sourceBones = source.bones;
  61662. var nBones;
  61663. var i;
  61664. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  61665. boneDict[sourceBones[i].name] = sourceBones[i];
  61666. }
  61667. if (this.bones.length !== sourceBones.length) {
  61668. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  61669. ret = false;
  61670. }
  61671. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  61672. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  61673. var boneName = this.bones[i].name;
  61674. var sourceBone = boneDict[boneName];
  61675. if (sourceBone) {
  61676. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  61677. }
  61678. else {
  61679. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  61680. ret = false;
  61681. }
  61682. }
  61683. // do not call createAnimationRange(), since it also is done to bones, which was already done
  61684. var range = source.getAnimationRange(name);
  61685. if (range) {
  61686. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  61687. }
  61688. return ret;
  61689. };
  61690. Skeleton.prototype.returnToRest = function () {
  61691. for (var index = 0; index < this.bones.length; index++) {
  61692. this.bones[index].returnToRest();
  61693. }
  61694. };
  61695. Skeleton.prototype._getHighestAnimationFrame = function () {
  61696. var ret = 0;
  61697. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61698. if (this.bones[i].animations[0]) {
  61699. var highest = this.bones[i].animations[0].getHighestFrame();
  61700. if (ret < highest) {
  61701. ret = highest;
  61702. }
  61703. }
  61704. }
  61705. return ret;
  61706. };
  61707. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  61708. var range = this.getAnimationRange(name);
  61709. if (!range) {
  61710. return null;
  61711. }
  61712. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  61713. };
  61714. Skeleton.prototype._markAsDirty = function () {
  61715. this._isDirty = true;
  61716. };
  61717. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  61718. this._meshesWithPoseMatrix.push(mesh);
  61719. };
  61720. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  61721. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  61722. if (index > -1) {
  61723. this._meshesWithPoseMatrix.splice(index, 1);
  61724. }
  61725. };
  61726. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  61727. this.onBeforeComputeObservable.notifyObservers(this);
  61728. for (var index = 0; index < this.bones.length; index++) {
  61729. var bone = this.bones[index];
  61730. var parentBone = bone.getParent();
  61731. if (parentBone) {
  61732. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  61733. }
  61734. else {
  61735. if (initialSkinMatrix) {
  61736. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  61737. }
  61738. else {
  61739. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  61740. }
  61741. }
  61742. if (bone._index !== -1) {
  61743. var mappedIndex = bone._index === null ? index : bone._index;
  61744. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  61745. }
  61746. }
  61747. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  61748. };
  61749. Skeleton.prototype.prepare = function () {
  61750. if (!this._isDirty) {
  61751. return;
  61752. }
  61753. if (this.needInitialSkinMatrix) {
  61754. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  61755. var mesh = this._meshesWithPoseMatrix[index];
  61756. var poseMatrix = mesh.getPoseMatrix();
  61757. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  61758. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61759. }
  61760. if (this._synchronizedWithMesh !== mesh) {
  61761. this._synchronizedWithMesh = mesh;
  61762. // Prepare bones
  61763. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  61764. var bone = this.bones[boneIndex];
  61765. if (!bone.getParent()) {
  61766. var matrix = bone.getBaseMatrix();
  61767. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  61768. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  61769. }
  61770. }
  61771. }
  61772. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  61773. }
  61774. }
  61775. else {
  61776. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  61777. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61778. }
  61779. this._computeTransformMatrices(this._transformMatrices, null);
  61780. }
  61781. this._isDirty = false;
  61782. this._scene._activeBones.addCount(this.bones.length, false);
  61783. };
  61784. Skeleton.prototype.getAnimatables = function () {
  61785. if (!this._animatables || this._animatables.length !== this.bones.length) {
  61786. this._animatables = [];
  61787. for (var index = 0; index < this.bones.length; index++) {
  61788. this._animatables.push(this.bones[index]);
  61789. }
  61790. }
  61791. return this._animatables;
  61792. };
  61793. Skeleton.prototype.clone = function (name, id) {
  61794. var result = new Skeleton(name, id || name, this._scene);
  61795. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  61796. for (var index = 0; index < this.bones.length; index++) {
  61797. var source = this.bones[index];
  61798. var parentBone = null;
  61799. var parent_1 = source.getParent();
  61800. if (parent_1) {
  61801. var parentIndex = this.bones.indexOf(parent_1);
  61802. parentBone = result.bones[parentIndex];
  61803. }
  61804. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  61805. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  61806. }
  61807. if (this._ranges) {
  61808. result._ranges = {};
  61809. for (var rangeName in this._ranges) {
  61810. var range = this._ranges[rangeName];
  61811. if (range) {
  61812. result._ranges[rangeName] = range.clone();
  61813. }
  61814. }
  61815. }
  61816. this._isDirty = true;
  61817. return result;
  61818. };
  61819. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  61820. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  61821. this.bones.forEach(function (bone) {
  61822. bone.animations.forEach(function (animation) {
  61823. animation.enableBlending = true;
  61824. animation.blendingSpeed = blendingSpeed;
  61825. });
  61826. });
  61827. };
  61828. Skeleton.prototype.dispose = function () {
  61829. this._meshesWithPoseMatrix = [];
  61830. // Animations
  61831. this.getScene().stopAnimation(this);
  61832. // Remove from scene
  61833. this.getScene().removeSkeleton(this);
  61834. };
  61835. Skeleton.prototype.serialize = function () {
  61836. var serializationObject = {};
  61837. serializationObject.name = this.name;
  61838. serializationObject.id = this.id;
  61839. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  61840. serializationObject.bones = [];
  61841. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  61842. for (var index = 0; index < this.bones.length; index++) {
  61843. var bone = this.bones[index];
  61844. var parent_2 = bone.getParent();
  61845. var serializedBone = {
  61846. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  61847. name: bone.name,
  61848. matrix: bone.getBaseMatrix().toArray(),
  61849. rest: bone.getRestPose().toArray()
  61850. };
  61851. serializationObject.bones.push(serializedBone);
  61852. if (bone.length) {
  61853. serializedBone.length = bone.length;
  61854. }
  61855. if (bone.animations && bone.animations.length > 0) {
  61856. serializedBone.animation = bone.animations[0].serialize();
  61857. }
  61858. serializationObject.ranges = [];
  61859. for (var name in this._ranges) {
  61860. var source = this._ranges[name];
  61861. if (!source) {
  61862. continue;
  61863. }
  61864. var range = {};
  61865. range.name = name;
  61866. range.from = source.from;
  61867. range.to = source.to;
  61868. serializationObject.ranges.push(range);
  61869. }
  61870. }
  61871. return serializationObject;
  61872. };
  61873. Skeleton.Parse = function (parsedSkeleton, scene) {
  61874. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  61875. if (parsedSkeleton.dimensionsAtRest) {
  61876. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  61877. }
  61878. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  61879. var index;
  61880. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  61881. var parsedBone = parsedSkeleton.bones[index];
  61882. var parentBone = null;
  61883. if (parsedBone.parentBoneIndex > -1) {
  61884. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  61885. }
  61886. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  61887. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  61888. if (parsedBone.length) {
  61889. bone.length = parsedBone.length;
  61890. }
  61891. if (parsedBone.animation) {
  61892. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  61893. }
  61894. }
  61895. // placed after bones, so createAnimationRange can cascade down
  61896. if (parsedSkeleton.ranges) {
  61897. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  61898. var data = parsedSkeleton.ranges[index];
  61899. skeleton.createAnimationRange(data.name, data.from, data.to);
  61900. }
  61901. }
  61902. return skeleton;
  61903. };
  61904. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  61905. if (forceUpdate === void 0) { forceUpdate = false; }
  61906. var renderId = this._scene.getRenderId();
  61907. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  61908. this.bones[0].computeAbsoluteTransforms();
  61909. this._lastAbsoluteTransformsUpdateId = renderId;
  61910. }
  61911. };
  61912. Skeleton.prototype.getPoseMatrix = function () {
  61913. var poseMatrix = null;
  61914. if (this._meshesWithPoseMatrix.length > 0) {
  61915. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  61916. }
  61917. return poseMatrix;
  61918. };
  61919. Skeleton.prototype.sortBones = function () {
  61920. var bones = new Array();
  61921. var visited = new Array(this.bones.length);
  61922. for (var index = 0; index < this.bones.length; index++) {
  61923. this._sortBones(index, bones, visited);
  61924. }
  61925. this.bones = bones;
  61926. };
  61927. Skeleton.prototype._sortBones = function (index, bones, visited) {
  61928. if (visited[index]) {
  61929. return;
  61930. }
  61931. visited[index] = true;
  61932. var bone = this.bones[index];
  61933. if (bone._index === undefined) {
  61934. bone._index = index;
  61935. }
  61936. var parentBone = bone.getParent();
  61937. if (parentBone) {
  61938. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  61939. }
  61940. bones.push(bone);
  61941. };
  61942. return Skeleton;
  61943. }());
  61944. BABYLON.Skeleton = Skeleton;
  61945. })(BABYLON || (BABYLON = {}));
  61946. //# sourceMappingURL=babylon.skeleton.js.map
  61947. var BABYLON;
  61948. (function (BABYLON) {
  61949. var SphericalPolynomial = /** @class */ (function () {
  61950. function SphericalPolynomial() {
  61951. this.x = BABYLON.Vector3.Zero();
  61952. this.y = BABYLON.Vector3.Zero();
  61953. this.z = BABYLON.Vector3.Zero();
  61954. this.xx = BABYLON.Vector3.Zero();
  61955. this.yy = BABYLON.Vector3.Zero();
  61956. this.zz = BABYLON.Vector3.Zero();
  61957. this.xy = BABYLON.Vector3.Zero();
  61958. this.yz = BABYLON.Vector3.Zero();
  61959. this.zx = BABYLON.Vector3.Zero();
  61960. }
  61961. SphericalPolynomial.prototype.addAmbient = function (color) {
  61962. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  61963. this.xx = this.xx.add(colorVector);
  61964. this.yy = this.yy.add(colorVector);
  61965. this.zz = this.zz.add(colorVector);
  61966. };
  61967. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  61968. var result = new SphericalPolynomial();
  61969. result.x = harmonics.L11.scale(1.02333);
  61970. result.y = harmonics.L1_1.scale(1.02333);
  61971. result.z = harmonics.L10.scale(1.02333);
  61972. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  61973. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  61974. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  61975. result.yz = harmonics.L2_1.scale(0.858086);
  61976. result.zx = harmonics.L21.scale(0.858086);
  61977. result.xy = harmonics.L2_2.scale(0.858086);
  61978. result.scale(1.0 / Math.PI);
  61979. return result;
  61980. };
  61981. SphericalPolynomial.prototype.scale = function (scale) {
  61982. this.x = this.x.scale(scale);
  61983. this.y = this.y.scale(scale);
  61984. this.z = this.z.scale(scale);
  61985. this.xx = this.xx.scale(scale);
  61986. this.yy = this.yy.scale(scale);
  61987. this.zz = this.zz.scale(scale);
  61988. this.yz = this.yz.scale(scale);
  61989. this.zx = this.zx.scale(scale);
  61990. this.xy = this.xy.scale(scale);
  61991. };
  61992. return SphericalPolynomial;
  61993. }());
  61994. BABYLON.SphericalPolynomial = SphericalPolynomial;
  61995. var SphericalHarmonics = /** @class */ (function () {
  61996. function SphericalHarmonics() {
  61997. this.L00 = BABYLON.Vector3.Zero();
  61998. this.L1_1 = BABYLON.Vector3.Zero();
  61999. this.L10 = BABYLON.Vector3.Zero();
  62000. this.L11 = BABYLON.Vector3.Zero();
  62001. this.L2_2 = BABYLON.Vector3.Zero();
  62002. this.L2_1 = BABYLON.Vector3.Zero();
  62003. this.L20 = BABYLON.Vector3.Zero();
  62004. this.L21 = BABYLON.Vector3.Zero();
  62005. this.L22 = BABYLON.Vector3.Zero();
  62006. }
  62007. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62008. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62009. var c = colorVector.scale(deltaSolidAngle);
  62010. this.L00 = this.L00.add(c.scale(0.282095));
  62011. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62012. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62013. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62014. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62015. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62016. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62017. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62018. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62019. };
  62020. SphericalHarmonics.prototype.scale = function (scale) {
  62021. this.L00 = this.L00.scale(scale);
  62022. this.L1_1 = this.L1_1.scale(scale);
  62023. this.L10 = this.L10.scale(scale);
  62024. this.L11 = this.L11.scale(scale);
  62025. this.L2_2 = this.L2_2.scale(scale);
  62026. this.L2_1 = this.L2_1.scale(scale);
  62027. this.L20 = this.L20.scale(scale);
  62028. this.L21 = this.L21.scale(scale);
  62029. this.L22 = this.L22.scale(scale);
  62030. };
  62031. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62032. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62033. //
  62034. // E_lm = A_l * L_lm
  62035. //
  62036. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62037. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62038. // the scaling factors are given in equation 9.
  62039. // Constant (Band 0)
  62040. this.L00 = this.L00.scale(3.141593);
  62041. // Linear (Band 1)
  62042. this.L1_1 = this.L1_1.scale(2.094395);
  62043. this.L10 = this.L10.scale(2.094395);
  62044. this.L11 = this.L11.scale(2.094395);
  62045. // Quadratic (Band 2)
  62046. this.L2_2 = this.L2_2.scale(0.785398);
  62047. this.L2_1 = this.L2_1.scale(0.785398);
  62048. this.L20 = this.L20.scale(0.785398);
  62049. this.L21 = this.L21.scale(0.785398);
  62050. this.L22 = this.L22.scale(0.785398);
  62051. };
  62052. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62053. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62054. // L = (1/pi) * E * rho
  62055. //
  62056. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62057. this.scale(1.0 / Math.PI);
  62058. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62059. // (The pixel shader must apply albedo after texture fetches, etc).
  62060. };
  62061. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62062. var result = new SphericalHarmonics();
  62063. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62064. result.L1_1 = polynomial.y.scale(0.977204);
  62065. result.L10 = polynomial.z.scale(0.977204);
  62066. result.L11 = polynomial.x.scale(0.977204);
  62067. result.L2_2 = polynomial.xy.scale(1.16538);
  62068. result.L2_1 = polynomial.yz.scale(1.16538);
  62069. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62070. result.L21 = polynomial.zx.scale(1.16538);
  62071. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62072. result.scale(Math.PI);
  62073. return result;
  62074. };
  62075. return SphericalHarmonics;
  62076. }());
  62077. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62078. })(BABYLON || (BABYLON = {}));
  62079. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62080. var BABYLON;
  62081. (function (BABYLON) {
  62082. var Internals;
  62083. (function (Internals) {
  62084. var FileFaceOrientation = /** @class */ (function () {
  62085. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62086. this.name = name;
  62087. this.worldAxisForNormal = worldAxisForNormal;
  62088. this.worldAxisForFileX = worldAxisForFileX;
  62089. this.worldAxisForFileY = worldAxisForFileY;
  62090. }
  62091. return FileFaceOrientation;
  62092. }());
  62093. ;
  62094. /**
  62095. * Helper class dealing with the extraction of spherical polynomial dataArray
  62096. * from a cube map.
  62097. */
  62098. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62099. function CubeMapToSphericalPolynomialTools() {
  62100. }
  62101. /**
  62102. * Converts a texture to the according Spherical Polynomial data.
  62103. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62104. *
  62105. * @param texture The texture to extract the information from.
  62106. * @return The Spherical Polynomial data.
  62107. */
  62108. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62109. if (!texture.isCube) {
  62110. // Only supports cube Textures currently.
  62111. return null;
  62112. }
  62113. var size = texture.getSize().width;
  62114. var right = texture.readPixels(0);
  62115. var left = texture.readPixels(1);
  62116. var up;
  62117. var down;
  62118. if (texture.isRenderTarget) {
  62119. up = texture.readPixels(3);
  62120. down = texture.readPixels(2);
  62121. }
  62122. else {
  62123. up = texture.readPixels(2);
  62124. down = texture.readPixels(3);
  62125. }
  62126. var front = texture.readPixels(4);
  62127. var back = texture.readPixels(5);
  62128. var gammaSpace = texture.gammaSpace;
  62129. // Always read as RGBA.
  62130. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62131. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62132. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62133. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62134. }
  62135. var cubeInfo = {
  62136. size: size,
  62137. right: right,
  62138. left: left,
  62139. up: up,
  62140. down: down,
  62141. front: front,
  62142. back: back,
  62143. format: format,
  62144. type: type,
  62145. gammaSpace: gammaSpace,
  62146. };
  62147. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62148. };
  62149. /**
  62150. * Converts a cubemap to the according Spherical Polynomial data.
  62151. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62152. *
  62153. * @param cubeInfo The Cube map to extract the information from.
  62154. * @return The Spherical Polynomial data.
  62155. */
  62156. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62157. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62158. var totalSolidAngle = 0.0;
  62159. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62160. var du = 2.0 / cubeInfo.size;
  62161. var dv = du;
  62162. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62163. var minUV = du * 0.5 - 1.0;
  62164. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62165. var fileFace = this.FileFaces[faceIndex];
  62166. var dataArray = cubeInfo[fileFace.name];
  62167. var v = minUV;
  62168. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62169. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62170. // Because SP is still linear, so summation is fine in that basis.
  62171. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62172. for (var y = 0; y < cubeInfo.size; y++) {
  62173. var u = minUV;
  62174. for (var x = 0; x < cubeInfo.size; x++) {
  62175. // World direction (not normalised)
  62176. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62177. worldDirection.normalize();
  62178. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62179. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62180. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62181. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62182. // Handle Integer types.
  62183. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62184. r /= 255;
  62185. g /= 255;
  62186. b /= 255;
  62187. }
  62188. // Handle Gamma space textures.
  62189. if (cubeInfo.gammaSpace) {
  62190. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62191. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62192. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62193. }
  62194. var color = new BABYLON.Color3(r, g, b);
  62195. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62196. totalSolidAngle += deltaSolidAngle;
  62197. u += du;
  62198. }
  62199. v += dv;
  62200. }
  62201. }
  62202. // Solid angle for entire sphere is 4*pi
  62203. var sphereSolidAngle = 4.0 * Math.PI;
  62204. // Adjust the solid angle to allow for how many faces we processed.
  62205. var facesProcessed = 6.0;
  62206. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62207. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62208. // This is needed because the numerical integration over the cube uses a
  62209. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62210. // and also to compensate for accumulative error due to float precision in the summation.
  62211. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62212. sphericalHarmonics.scale(correctionFactor);
  62213. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62214. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62215. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62216. };
  62217. CubeMapToSphericalPolynomialTools.FileFaces = [
  62218. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62219. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62220. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62221. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62222. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62223. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62224. ];
  62225. return CubeMapToSphericalPolynomialTools;
  62226. }());
  62227. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62228. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62229. })(BABYLON || (BABYLON = {}));
  62230. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62231. var BABYLON;
  62232. (function (BABYLON) {
  62233. var Internals;
  62234. (function (Internals) {
  62235. /**
  62236. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62237. */
  62238. var PanoramaToCubeMapTools = /** @class */ (function () {
  62239. function PanoramaToCubeMapTools() {
  62240. }
  62241. /**
  62242. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62243. *
  62244. * @param float32Array The source data.
  62245. * @param inputWidth The width of the input panorama.
  62246. * @param inputhHeight The height of the input panorama.
  62247. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62248. * @return The cubemap data
  62249. */
  62250. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62251. if (!float32Array) {
  62252. throw "ConvertPanoramaToCubemap: input cannot be null";
  62253. }
  62254. if (float32Array.length != inputWidth * inputHeight * 3) {
  62255. throw "ConvertPanoramaToCubemap: input size is wrong";
  62256. }
  62257. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62258. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62259. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62260. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62261. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62262. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62263. return {
  62264. front: textureFront,
  62265. back: textureBack,
  62266. left: textureLeft,
  62267. right: textureRight,
  62268. up: textureUp,
  62269. down: textureDown,
  62270. size: size,
  62271. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62272. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62273. gammaSpace: false,
  62274. };
  62275. };
  62276. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62277. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62278. var textureArray = new Float32Array(buffer);
  62279. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62280. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62281. var dy = 1 / texSize;
  62282. var fy = 0;
  62283. for (var y = 0; y < texSize; y++) {
  62284. var xv1 = faceData[0];
  62285. var xv2 = faceData[2];
  62286. for (var x = 0; x < texSize; x++) {
  62287. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62288. v.normalize();
  62289. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62290. // 3 channels per pixels
  62291. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62292. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62293. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62294. xv1 = xv1.add(rotDX1);
  62295. xv2 = xv2.add(rotDX2);
  62296. }
  62297. fy += dy;
  62298. }
  62299. return textureArray;
  62300. };
  62301. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62302. var theta = Math.atan2(vDir.z, vDir.x);
  62303. var phi = Math.acos(vDir.y);
  62304. while (theta < -Math.PI)
  62305. theta += 2 * Math.PI;
  62306. while (theta > Math.PI)
  62307. theta -= 2 * Math.PI;
  62308. var dx = theta / Math.PI;
  62309. var dy = phi / Math.PI;
  62310. // recenter.
  62311. dx = dx * 0.5 + 0.5;
  62312. var px = Math.round(dx * inputWidth);
  62313. if (px < 0)
  62314. px = 0;
  62315. else if (px >= inputWidth)
  62316. px = inputWidth - 1;
  62317. var py = Math.round(dy * inputHeight);
  62318. if (py < 0)
  62319. py = 0;
  62320. else if (py >= inputHeight)
  62321. py = inputHeight - 1;
  62322. var inputY = (inputHeight - py - 1);
  62323. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62324. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62325. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62326. return {
  62327. r: r,
  62328. g: g,
  62329. b: b
  62330. };
  62331. };
  62332. PanoramaToCubeMapTools.FACE_FRONT = [
  62333. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62334. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62335. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62336. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62337. ];
  62338. PanoramaToCubeMapTools.FACE_BACK = [
  62339. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62340. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62341. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62342. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62343. ];
  62344. PanoramaToCubeMapTools.FACE_RIGHT = [
  62345. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62346. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62347. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62348. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62349. ];
  62350. PanoramaToCubeMapTools.FACE_LEFT = [
  62351. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62352. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62353. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62354. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62355. ];
  62356. PanoramaToCubeMapTools.FACE_DOWN = [
  62357. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62358. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62359. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62360. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62361. ];
  62362. PanoramaToCubeMapTools.FACE_UP = [
  62363. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62364. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62365. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62366. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62367. ];
  62368. return PanoramaToCubeMapTools;
  62369. }());
  62370. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62371. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62372. })(BABYLON || (BABYLON = {}));
  62373. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62374. var BABYLON;
  62375. (function (BABYLON) {
  62376. var Internals;
  62377. (function (Internals) {
  62378. ;
  62379. /**
  62380. * This groups tools to convert HDR texture to native colors array.
  62381. */
  62382. var HDRTools = /** @class */ (function () {
  62383. function HDRTools() {
  62384. }
  62385. HDRTools.Ldexp = function (mantissa, exponent) {
  62386. if (exponent > 1023) {
  62387. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62388. }
  62389. if (exponent < -1074) {
  62390. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62391. }
  62392. return mantissa * Math.pow(2, exponent);
  62393. };
  62394. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62395. if (exponent > 0) {
  62396. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62397. float32array[index + 0] = red * exponent;
  62398. float32array[index + 1] = green * exponent;
  62399. float32array[index + 2] = blue * exponent;
  62400. }
  62401. else {
  62402. float32array[index + 0] = 0;
  62403. float32array[index + 1] = 0;
  62404. float32array[index + 2] = 0;
  62405. }
  62406. };
  62407. HDRTools.readStringLine = function (uint8array, startIndex) {
  62408. var line = "";
  62409. var character = "";
  62410. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62411. character = String.fromCharCode(uint8array[i]);
  62412. if (character == "\n") {
  62413. break;
  62414. }
  62415. line += character;
  62416. }
  62417. return line;
  62418. };
  62419. /**
  62420. * Reads header information from an RGBE texture stored in a native array.
  62421. * More information on this format are available here:
  62422. * https://en.wikipedia.org/wiki/RGBE_image_format
  62423. *
  62424. * @param uint8array The binary file stored in native array.
  62425. * @return The header information.
  62426. */
  62427. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62428. var height = 0;
  62429. var width = 0;
  62430. var line = this.readStringLine(uint8array, 0);
  62431. if (line[0] != '#' || line[1] != '?') {
  62432. throw "Bad HDR Format.";
  62433. }
  62434. var endOfHeader = false;
  62435. var findFormat = false;
  62436. var lineIndex = 0;
  62437. do {
  62438. lineIndex += (line.length + 1);
  62439. line = this.readStringLine(uint8array, lineIndex);
  62440. if (line == "FORMAT=32-bit_rle_rgbe") {
  62441. findFormat = true;
  62442. }
  62443. else if (line.length == 0) {
  62444. endOfHeader = true;
  62445. }
  62446. } while (!endOfHeader);
  62447. if (!findFormat) {
  62448. throw "HDR Bad header format, unsupported FORMAT";
  62449. }
  62450. lineIndex += (line.length + 1);
  62451. line = this.readStringLine(uint8array, lineIndex);
  62452. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62453. var match = sizeRegexp.exec(line);
  62454. // TODO. Support +Y and -X if needed.
  62455. if (!match || match.length < 3) {
  62456. throw "HDR Bad header format, no size";
  62457. }
  62458. width = parseInt(match[2]);
  62459. height = parseInt(match[1]);
  62460. if (width < 8 || width > 0x7fff) {
  62461. throw "HDR Bad header format, unsupported size";
  62462. }
  62463. lineIndex += (line.length + 1);
  62464. return {
  62465. height: height,
  62466. width: width,
  62467. dataPosition: lineIndex
  62468. };
  62469. };
  62470. /**
  62471. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62472. * This RGBE texture needs to store the information as a panorama.
  62473. *
  62474. * More information on this format are available here:
  62475. * https://en.wikipedia.org/wiki/RGBE_image_format
  62476. *
  62477. * @param buffer The binary file stored in an array buffer.
  62478. * @param size The expected size of the extracted cubemap.
  62479. * @return The Cube Map information.
  62480. */
  62481. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62482. var uint8array = new Uint8Array(buffer);
  62483. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62484. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62485. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62486. return cubeMapData;
  62487. };
  62488. /**
  62489. * Returns the pixels data extracted from an RGBE texture.
  62490. * This pixels will be stored left to right up to down in the R G B order in one array.
  62491. *
  62492. * More information on this format are available here:
  62493. * https://en.wikipedia.org/wiki/RGBE_image_format
  62494. *
  62495. * @param uint8array The binary file stored in an array buffer.
  62496. * @param hdrInfo The header information of the file.
  62497. * @return The pixels data in RGB right to left up to down order.
  62498. */
  62499. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62500. // Keep for multi format supports.
  62501. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62502. };
  62503. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62504. var num_scanlines = hdrInfo.height;
  62505. var scanline_width = hdrInfo.width;
  62506. var a, b, c, d, count;
  62507. var dataIndex = hdrInfo.dataPosition;
  62508. var index = 0, endIndex = 0, i = 0;
  62509. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62510. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62511. // 3 channels of 4 bytes per pixel in float.
  62512. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62513. var resultArray = new Float32Array(resultBuffer);
  62514. // read in each successive scanline
  62515. while (num_scanlines > 0) {
  62516. a = uint8array[dataIndex++];
  62517. b = uint8array[dataIndex++];
  62518. c = uint8array[dataIndex++];
  62519. d = uint8array[dataIndex++];
  62520. if (a != 2 || b != 2 || (c & 0x80)) {
  62521. // this file is not run length encoded
  62522. throw "HDR Bad header format, not RLE";
  62523. }
  62524. if (((c << 8) | d) != scanline_width) {
  62525. throw "HDR Bad header format, wrong scan line width";
  62526. }
  62527. index = 0;
  62528. // read each of the four channels for the scanline into the buffer
  62529. for (i = 0; i < 4; i++) {
  62530. endIndex = (i + 1) * scanline_width;
  62531. while (index < endIndex) {
  62532. a = uint8array[dataIndex++];
  62533. b = uint8array[dataIndex++];
  62534. if (a > 128) {
  62535. // a run of the same value
  62536. count = a - 128;
  62537. if ((count == 0) || (count > endIndex - index)) {
  62538. throw "HDR Bad Format, bad scanline data (run)";
  62539. }
  62540. while (count-- > 0) {
  62541. scanLineArray[index++] = b;
  62542. }
  62543. }
  62544. else {
  62545. // a non-run
  62546. count = a;
  62547. if ((count == 0) || (count > endIndex - index)) {
  62548. throw "HDR Bad Format, bad scanline data (non-run)";
  62549. }
  62550. scanLineArray[index++] = b;
  62551. if (--count > 0) {
  62552. for (var j = 0; j < count; j++) {
  62553. scanLineArray[index++] = uint8array[dataIndex++];
  62554. }
  62555. }
  62556. }
  62557. }
  62558. }
  62559. // now convert data from buffer into floats
  62560. for (i = 0; i < scanline_width; i++) {
  62561. a = scanLineArray[i];
  62562. b = scanLineArray[i + scanline_width];
  62563. c = scanLineArray[i + 2 * scanline_width];
  62564. d = scanLineArray[i + 3 * scanline_width];
  62565. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  62566. }
  62567. num_scanlines--;
  62568. }
  62569. return resultArray;
  62570. };
  62571. return HDRTools;
  62572. }());
  62573. Internals.HDRTools = HDRTools;
  62574. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62575. })(BABYLON || (BABYLON = {}));
  62576. //# sourceMappingURL=babylon.hdr.js.map
  62577. var BABYLON;
  62578. (function (BABYLON) {
  62579. /**
  62580. * This represents a texture coming from an HDR input.
  62581. *
  62582. * The only supported format is currently panorama picture stored in RGBE format.
  62583. * Example of such files can be found on HDRLib: http://hdrlib.com/
  62584. */
  62585. var HDRCubeTexture = /** @class */ (function (_super) {
  62586. __extends(HDRCubeTexture, _super);
  62587. /**
  62588. * Instantiates an HDRTexture from the following parameters.
  62589. *
  62590. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  62591. * @param scene The scene the texture will be used in
  62592. * @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.
  62593. * @param noMipmap Forces to not generate the mipmap if true
  62594. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  62595. * @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)
  62596. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  62597. */
  62598. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  62599. if (noMipmap === void 0) { noMipmap = false; }
  62600. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62601. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62602. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62603. if (onLoad === void 0) { onLoad = null; }
  62604. if (onError === void 0) { onError = null; }
  62605. var _this = _super.call(this, scene) || this;
  62606. _this._useInGammaSpace = false;
  62607. _this._generateHarmonics = true;
  62608. _this._isBABYLONPreprocessed = false;
  62609. _this._onLoad = null;
  62610. _this._onError = null;
  62611. /**
  62612. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  62613. */
  62614. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62615. /**
  62616. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  62617. * This is usefull at run time to apply the good shader.
  62618. */
  62619. _this.isPMREM = false;
  62620. _this._isBlocking = true;
  62621. if (!url) {
  62622. return _this;
  62623. }
  62624. _this.name = url;
  62625. _this.url = url;
  62626. _this.hasAlpha = false;
  62627. _this.isCube = true;
  62628. _this._textureMatrix = BABYLON.Matrix.Identity();
  62629. _this._onLoad = onLoad;
  62630. _this._onError = onError;
  62631. _this.gammaSpace = false;
  62632. var caps = scene.getEngine().getCaps();
  62633. if (size) {
  62634. _this._isBABYLONPreprocessed = false;
  62635. _this._noMipmap = noMipmap;
  62636. _this._size = size;
  62637. _this._useInGammaSpace = useInGammaSpace;
  62638. _this._usePMREMGenerator = usePMREMGenerator &&
  62639. caps.textureLOD &&
  62640. caps.textureFloat &&
  62641. !_this._useInGammaSpace;
  62642. }
  62643. else {
  62644. _this._isBABYLONPreprocessed = true;
  62645. _this._noMipmap = false;
  62646. _this._useInGammaSpace = false;
  62647. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  62648. !_this._useInGammaSpace;
  62649. }
  62650. _this.isPMREM = _this._usePMREMGenerator;
  62651. _this._texture = _this._getFromCache(url, _this._noMipmap);
  62652. if (!_this._texture) {
  62653. if (!scene.useDelayedTextureLoading) {
  62654. _this.loadTexture();
  62655. }
  62656. else {
  62657. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62658. }
  62659. }
  62660. return _this;
  62661. }
  62662. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  62663. /**
  62664. * Gets wether or not the texture is blocking during loading.
  62665. */
  62666. get: function () {
  62667. return this._isBlocking;
  62668. },
  62669. /**
  62670. * Sets wether or not the texture is blocking during loading.
  62671. */
  62672. set: function (value) {
  62673. this._isBlocking = value;
  62674. },
  62675. enumerable: true,
  62676. configurable: true
  62677. });
  62678. /**
  62679. * Occurs when the file is a preprocessed .babylon.hdr file.
  62680. */
  62681. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  62682. var _this = this;
  62683. var mipLevels = 0;
  62684. var floatArrayView = null;
  62685. var scene = this.getScene();
  62686. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  62687. var mips = new Array();
  62688. if (!floatArrayView) {
  62689. return mips;
  62690. }
  62691. var startIndex = 30;
  62692. for (var level = 0; level < mipLevels; level++) {
  62693. mips.push([]);
  62694. // Fill each pixel of the mip level.
  62695. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  62696. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62697. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  62698. mips[level].push(faceData);
  62699. startIndex += faceSize;
  62700. }
  62701. }
  62702. return mips;
  62703. } : null;
  62704. var callback = function (buffer) {
  62705. var scene = _this.getScene();
  62706. if (!scene) {
  62707. return null;
  62708. }
  62709. // Create Native Array Views
  62710. var intArrayView = new Int32Array(buffer);
  62711. floatArrayView = new Float32Array(buffer);
  62712. // Fill header.
  62713. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  62714. _this._size = intArrayView[1]; // CubeMap max mip face size.
  62715. // Update Texture Information.
  62716. if (!_this._texture) {
  62717. return null;
  62718. }
  62719. _this._texture.updateSize(_this._size, _this._size);
  62720. // Fill polynomial information.
  62721. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  62722. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  62723. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  62724. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  62725. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  62726. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  62727. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  62728. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  62729. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  62730. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  62731. _this.sphericalPolynomial = sphericalPolynomial;
  62732. // Fill pixel data.
  62733. mipLevels = intArrayView[29]; // Number of mip levels.
  62734. var startIndex = 30;
  62735. var data = [];
  62736. var faceSize = Math.pow(_this._size, 2) * 3;
  62737. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62738. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  62739. startIndex += faceSize;
  62740. }
  62741. var results = [];
  62742. var byteArray = null;
  62743. // Push each faces.
  62744. for (var k = 0; k < 6; k++) {
  62745. var dataFace = null;
  62746. // To be deprecated.
  62747. if (version === 1) {
  62748. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  62749. dataFace = data[j];
  62750. }
  62751. // If special cases.
  62752. if (!mipmapGenerator && dataFace) {
  62753. if (!scene.getEngine().getCaps().textureFloat) {
  62754. // 3 channels of 1 bytes per pixel in bytes.
  62755. var byteBuffer = new ArrayBuffer(faceSize);
  62756. byteArray = new Uint8Array(byteBuffer);
  62757. }
  62758. for (var i = 0; i < _this._size * _this._size; i++) {
  62759. // Put in gamma space if requested.
  62760. if (_this._useInGammaSpace) {
  62761. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62762. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62763. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62764. }
  62765. // Convert to int texture for fallback.
  62766. if (byteArray) {
  62767. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62768. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62769. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62770. // May use luminance instead if the result is not accurate.
  62771. var max = Math.max(Math.max(r, g), b);
  62772. if (max > 255) {
  62773. var scale = 255 / max;
  62774. r *= scale;
  62775. g *= scale;
  62776. b *= scale;
  62777. }
  62778. byteArray[(i * 3) + 0] = r;
  62779. byteArray[(i * 3) + 1] = g;
  62780. byteArray[(i * 3) + 2] = b;
  62781. }
  62782. }
  62783. }
  62784. // Fill the array accordingly.
  62785. if (byteArray) {
  62786. results.push(byteArray);
  62787. }
  62788. else {
  62789. results.push(dataFace);
  62790. }
  62791. }
  62792. return results;
  62793. };
  62794. if (scene) {
  62795. 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);
  62796. }
  62797. };
  62798. /**
  62799. * Occurs when the file is raw .hdr file.
  62800. */
  62801. HDRCubeTexture.prototype.loadHDRTexture = function () {
  62802. var _this = this;
  62803. var callback = function (buffer) {
  62804. var scene = _this.getScene();
  62805. if (!scene) {
  62806. return null;
  62807. }
  62808. // Extract the raw linear data.
  62809. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  62810. // Generate harmonics if needed.
  62811. if (_this._generateHarmonics) {
  62812. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  62813. _this.sphericalPolynomial = sphericalPolynomial;
  62814. }
  62815. var results = [];
  62816. var byteArray = null;
  62817. // Push each faces.
  62818. for (var j = 0; j < 6; j++) {
  62819. // Create uintarray fallback.
  62820. if (!scene.getEngine().getCaps().textureFloat) {
  62821. // 3 channels of 1 bytes per pixel in bytes.
  62822. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  62823. byteArray = new Uint8Array(byteBuffer);
  62824. }
  62825. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  62826. // If special cases.
  62827. if (_this._useInGammaSpace || byteArray) {
  62828. for (var i = 0; i < _this._size * _this._size; i++) {
  62829. // Put in gamma space if requested.
  62830. if (_this._useInGammaSpace) {
  62831. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62832. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62833. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62834. }
  62835. // Convert to int texture for fallback.
  62836. if (byteArray) {
  62837. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62838. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62839. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62840. // May use luminance instead if the result is not accurate.
  62841. var max = Math.max(Math.max(r, g), b);
  62842. if (max > 255) {
  62843. var scale = 255 / max;
  62844. r *= scale;
  62845. g *= scale;
  62846. b *= scale;
  62847. }
  62848. byteArray[(i * 3) + 0] = r;
  62849. byteArray[(i * 3) + 1] = g;
  62850. byteArray[(i * 3) + 2] = b;
  62851. }
  62852. }
  62853. }
  62854. if (byteArray) {
  62855. results.push(byteArray);
  62856. }
  62857. else {
  62858. results.push(dataFace);
  62859. }
  62860. }
  62861. return results;
  62862. };
  62863. var mipmapGenerator = null;
  62864. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  62865. // if (!this._noMipmap &&
  62866. // this._usePMREMGenerator) {
  62867. // mipmapGenerator = (data: ArrayBufferView[]) => {
  62868. // // Custom setup of the generator matching with the PBR shader values.
  62869. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  62870. // this._size,
  62871. // this._size,
  62872. // 0,
  62873. // 3,
  62874. // this.getScene().getEngine().getCaps().textureFloat,
  62875. // 2048,
  62876. // 0.25,
  62877. // false,
  62878. // true);
  62879. // return generator.filterCubeMap();
  62880. // };
  62881. // }
  62882. var scene = this.getScene();
  62883. if (scene) {
  62884. 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);
  62885. }
  62886. };
  62887. /**
  62888. * Starts the loading process of the texture.
  62889. */
  62890. HDRCubeTexture.prototype.loadTexture = function () {
  62891. if (this._isBABYLONPreprocessed) {
  62892. this.loadBabylonTexture();
  62893. }
  62894. else {
  62895. this.loadHDRTexture();
  62896. }
  62897. };
  62898. HDRCubeTexture.prototype.clone = function () {
  62899. var scene = this.getScene();
  62900. if (!scene) {
  62901. return this;
  62902. }
  62903. var size = (this._isBABYLONPreprocessed ? null : this._size);
  62904. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  62905. // Base texture
  62906. newTexture.level = this.level;
  62907. newTexture.wrapU = this.wrapU;
  62908. newTexture.wrapV = this.wrapV;
  62909. newTexture.coordinatesIndex = this.coordinatesIndex;
  62910. newTexture.coordinatesMode = this.coordinatesMode;
  62911. return newTexture;
  62912. };
  62913. // Methods
  62914. HDRCubeTexture.prototype.delayLoad = function () {
  62915. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62916. return;
  62917. }
  62918. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62919. this._texture = this._getFromCache(this.url, this._noMipmap);
  62920. if (!this._texture) {
  62921. this.loadTexture();
  62922. }
  62923. };
  62924. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  62925. return this._textureMatrix;
  62926. };
  62927. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62928. this._textureMatrix = value;
  62929. };
  62930. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62931. var texture = null;
  62932. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  62933. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  62934. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  62935. texture.name = parsedTexture.name;
  62936. texture.hasAlpha = parsedTexture.hasAlpha;
  62937. texture.level = parsedTexture.level;
  62938. texture.coordinatesMode = parsedTexture.coordinatesMode;
  62939. texture.isBlocking = parsedTexture.isBlocking;
  62940. }
  62941. return texture;
  62942. };
  62943. HDRCubeTexture.prototype.serialize = function () {
  62944. if (!this.name) {
  62945. return null;
  62946. }
  62947. var serializationObject = {};
  62948. serializationObject.name = this.name;
  62949. serializationObject.hasAlpha = this.hasAlpha;
  62950. serializationObject.isCube = true;
  62951. serializationObject.level = this.level;
  62952. serializationObject.size = this._size;
  62953. serializationObject.coordinatesMode = this.coordinatesMode;
  62954. serializationObject.useInGammaSpace = this._useInGammaSpace;
  62955. serializationObject.generateHarmonics = this._generateHarmonics;
  62956. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  62957. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  62958. serializationObject.customType = "BABYLON.HDRCubeTexture";
  62959. serializationObject.noMipmap = this._noMipmap;
  62960. serializationObject.isBlocking = this._isBlocking;
  62961. return serializationObject;
  62962. };
  62963. /**
  62964. * Saves as a file the data contained in the texture in a binary format.
  62965. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  62966. * as the spherical used in the lighting.
  62967. * @param url The HDR file url.
  62968. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  62969. * @param onError Method called if any error happens during download.
  62970. * @return The packed binary data.
  62971. */
  62972. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  62973. if (onError === void 0) { onError = null; }
  62974. var callback = function (buffer) {
  62975. var data = new Blob([buffer], { type: 'application/octet-stream' });
  62976. // Returns a URL you can use as a href.
  62977. var objUrl = window.URL.createObjectURL(data);
  62978. // Simulates a link to it and click to dowload.
  62979. var a = document.createElement("a");
  62980. document.body.appendChild(a);
  62981. a.style.display = "none";
  62982. a.href = objUrl;
  62983. a.download = "envmap.babylon.hdr";
  62984. a.click();
  62985. };
  62986. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  62987. };
  62988. /**
  62989. * Serializes the data contained in the texture in a binary format.
  62990. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  62991. * as the spherical used in the lighting.
  62992. * @param url The HDR file url.
  62993. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  62994. * @param onError Method called if any error happens during download.
  62995. * @return The packed binary data.
  62996. */
  62997. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  62998. if (onError === void 0) { onError = null; }
  62999. // Needs the url tho create the texture.
  63000. if (!url) {
  63001. return;
  63002. }
  63003. // Check Power of two size.
  63004. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63005. return;
  63006. }
  63007. // Coming Back in 3.x.
  63008. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63009. };
  63010. HDRCubeTexture._facesMapping = [
  63011. "right",
  63012. "left",
  63013. "up",
  63014. "down",
  63015. "front",
  63016. "back"
  63017. ];
  63018. return HDRCubeTexture;
  63019. }(BABYLON.BaseTexture));
  63020. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63021. })(BABYLON || (BABYLON = {}));
  63022. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63023. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63024. // Huge respect for a such great lib.
  63025. // Earcut license:
  63026. // Copyright (c) 2016, Mapbox
  63027. //
  63028. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63029. // with or without fee is hereby granted, provided that the above copyright notice
  63030. // and this permission notice appear in all copies.
  63031. //
  63032. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63033. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63034. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63035. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63036. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63037. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63038. // THIS SOFTWARE.
  63039. var Earcut;
  63040. (function (Earcut) {
  63041. /**
  63042. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63043. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63044. * @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).
  63045. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63046. */
  63047. function earcut(data, holeIndices, dim) {
  63048. dim = dim || 2;
  63049. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63050. if (!outerNode)
  63051. return triangles;
  63052. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63053. if (hasHoles)
  63054. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63055. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63056. if (data.length > 80 * dim) {
  63057. minX = maxX = data[0];
  63058. minY = maxY = data[1];
  63059. for (var i = dim; i < outerLen; i += dim) {
  63060. x = data[i];
  63061. y = data[i + 1];
  63062. if (x < minX)
  63063. minX = x;
  63064. if (y < minY)
  63065. minY = y;
  63066. if (x > maxX)
  63067. maxX = x;
  63068. if (y > maxY)
  63069. maxY = y;
  63070. }
  63071. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63072. size = Math.max(maxX - minX, maxY - minY);
  63073. }
  63074. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63075. return triangles;
  63076. }
  63077. Earcut.earcut = earcut;
  63078. var Node = /** @class */ (function () {
  63079. function Node(i, x, y) {
  63080. this.i = i;
  63081. this.x = x;
  63082. this.y = y;
  63083. this.prev = null;
  63084. this.next = null;
  63085. this.z = null;
  63086. this.prevZ = null;
  63087. this.nextZ = null;
  63088. this.steiner = false;
  63089. }
  63090. return Node;
  63091. }());
  63092. // create a circular doubly linked list from polygon points in the specified winding order
  63093. function linkedList(data, start, end, dim, clockwise) {
  63094. var i, last = null;
  63095. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63096. for (i = start; i < end; i += dim)
  63097. last = insertNode(i, data[i], data[i + 1], last);
  63098. }
  63099. else {
  63100. for (i = end - dim; i >= start; i -= dim)
  63101. last = insertNode(i, data[i], data[i + 1], last);
  63102. }
  63103. if (last && equals(last, last.next)) {
  63104. removeNode(last);
  63105. last = last.next;
  63106. }
  63107. return last;
  63108. }
  63109. // eliminate colinear or duplicate points
  63110. function filterPoints(start, end) {
  63111. if (!start)
  63112. return start;
  63113. if (!end)
  63114. end = start;
  63115. var p = start, again;
  63116. do {
  63117. again = false;
  63118. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63119. removeNode(p);
  63120. p = end = p.prev;
  63121. if (p === p.next)
  63122. return undefined;
  63123. again = true;
  63124. }
  63125. else {
  63126. p = p.next;
  63127. }
  63128. } while (again || p !== end);
  63129. return end;
  63130. }
  63131. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63132. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63133. if (!ear)
  63134. return;
  63135. // interlink polygon nodes in z-order
  63136. if (!pass && size)
  63137. indexCurve(ear, minX, minY, size);
  63138. var stop = ear, prev, next;
  63139. // iterate through ears, slicing them one by one
  63140. while (ear.prev !== ear.next) {
  63141. prev = ear.prev;
  63142. next = ear.next;
  63143. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63144. // cut off the triangle
  63145. triangles.push(prev.i / dim);
  63146. triangles.push(ear.i / dim);
  63147. triangles.push(next.i / dim);
  63148. removeNode(ear);
  63149. // skipping the next vertice leads to less sliver triangles
  63150. ear = next.next;
  63151. stop = next.next;
  63152. continue;
  63153. }
  63154. ear = next;
  63155. // if we looped through the whole remaining polygon and can't find any more ears
  63156. if (ear === stop) {
  63157. // try filtering points and slicing again
  63158. if (!pass) {
  63159. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63160. // if this didn't work, try curing all small self-intersections locally
  63161. }
  63162. else if (pass === 1) {
  63163. ear = cureLocalIntersections(ear, triangles, dim);
  63164. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63165. // as a last resort, try splitting the remaining polygon into two
  63166. }
  63167. else if (pass === 2) {
  63168. splitEarcut(ear, triangles, dim, minX, minY, size);
  63169. }
  63170. break;
  63171. }
  63172. }
  63173. }
  63174. // check whether a polygon node forms a valid ear with adjacent nodes
  63175. function isEar(ear) {
  63176. var a = ear.prev, b = ear, c = ear.next;
  63177. if (area(a, b, c) >= 0)
  63178. return false; // reflex, can't be an ear
  63179. // now make sure we don't have other points inside the potential ear
  63180. var p = ear.next.next;
  63181. while (p !== ear.prev) {
  63182. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63183. area(p.prev, p, p.next) >= 0)
  63184. return false;
  63185. p = p.next;
  63186. }
  63187. return true;
  63188. }
  63189. function isEarHashed(ear, minX, minY, size) {
  63190. var a = ear.prev, b = ear, c = ear.next;
  63191. if (area(a, b, c) >= 0)
  63192. return false; // reflex, can't be an ear
  63193. // triangle bbox; min & max are calculated like this for speed
  63194. 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);
  63195. // z-order range for the current triangle bbox;
  63196. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63197. // first look for points inside the triangle in increasing z-order
  63198. var p = ear.nextZ;
  63199. while (p && p.z <= maxZ) {
  63200. if (p !== ear.prev &&
  63201. p !== ear.next &&
  63202. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63203. area(p.prev, p, p.next) >= 0)
  63204. return false;
  63205. p = p.nextZ;
  63206. }
  63207. // then look for points in decreasing z-order
  63208. p = ear.prevZ;
  63209. while (p && p.z >= minZ) {
  63210. if (p !== ear.prev &&
  63211. p !== ear.next &&
  63212. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63213. area(p.prev, p, p.next) >= 0)
  63214. return false;
  63215. p = p.prevZ;
  63216. }
  63217. return true;
  63218. }
  63219. // go through all polygon nodes and cure small local self-intersections
  63220. function cureLocalIntersections(start, triangles, dim) {
  63221. var p = start;
  63222. do {
  63223. var a = p.prev, b = p.next.next;
  63224. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63225. triangles.push(a.i / dim);
  63226. triangles.push(p.i / dim);
  63227. triangles.push(b.i / dim);
  63228. // remove two nodes involved
  63229. removeNode(p);
  63230. removeNode(p.next);
  63231. p = start = b;
  63232. }
  63233. p = p.next;
  63234. } while (p !== start);
  63235. return p;
  63236. }
  63237. // try splitting polygon into two and triangulate them independently
  63238. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63239. // look for a valid diagonal that divides the polygon into two
  63240. var a = start;
  63241. do {
  63242. var b = a.next.next;
  63243. while (b !== a.prev) {
  63244. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63245. // split the polygon in two by the diagonal
  63246. var c = splitPolygon(a, b);
  63247. // filter colinear points around the cuts
  63248. a = filterPoints(a, a.next);
  63249. c = filterPoints(c, c.next);
  63250. // run earcut on each half
  63251. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63252. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63253. return;
  63254. }
  63255. b = b.next;
  63256. }
  63257. a = a.next;
  63258. } while (a !== start);
  63259. }
  63260. // link every hole into the outer loop, producing a single-ring polygon without holes
  63261. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63262. var queue = [], i, len, start, end, list;
  63263. for (i = 0, len = holeIndices.length; i < len; i++) {
  63264. start = holeIndices[i] * dim;
  63265. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63266. list = linkedList(data, start, end, dim, false);
  63267. if (list === list.next)
  63268. list.steiner = true;
  63269. queue.push(getLeftmost(list));
  63270. }
  63271. queue.sort(compareX);
  63272. // process holes from left to right
  63273. for (i = 0; i < queue.length; i++) {
  63274. eliminateHole(queue[i], outerNode);
  63275. outerNode = filterPoints(outerNode, outerNode.next);
  63276. }
  63277. return outerNode;
  63278. }
  63279. function compareX(a, b) {
  63280. return a.x - b.x;
  63281. }
  63282. // find a bridge between vertices that connects hole with an outer ring and and link it
  63283. function eliminateHole(hole, outerNode) {
  63284. outerNode = findHoleBridge(hole, outerNode);
  63285. if (outerNode) {
  63286. var b = splitPolygon(outerNode, hole);
  63287. filterPoints(b, b.next);
  63288. }
  63289. }
  63290. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63291. function findHoleBridge(hole, outerNode) {
  63292. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63293. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63294. // segment's endpoint with lesser x will be potential connection point
  63295. do {
  63296. if (hy <= p.y && hy >= p.next.y) {
  63297. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63298. if (x <= hx && x > qx) {
  63299. qx = x;
  63300. if (x === hx) {
  63301. if (hy === p.y)
  63302. return p;
  63303. if (hy === p.next.y)
  63304. return p.next;
  63305. }
  63306. m = p.x < p.next.x ? p : p.next;
  63307. }
  63308. }
  63309. p = p.next;
  63310. } while (p !== outerNode);
  63311. if (!m)
  63312. return null;
  63313. if (hx === qx)
  63314. return m.prev; // hole touches outer segment; pick lower endpoint
  63315. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63316. // if there are no points found, we have a valid connection;
  63317. // otherwise choose the point of the minimum angle with the ray as connection point
  63318. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63319. p = m.next;
  63320. while (p !== stop) {
  63321. if (hx >= p.x &&
  63322. p.x >= mx &&
  63323. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63324. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63325. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63326. m = p;
  63327. tanMin = tan;
  63328. }
  63329. }
  63330. p = p.next;
  63331. }
  63332. return m;
  63333. }
  63334. // interlink polygon nodes in z-order
  63335. function indexCurve(start, minX, minY, size) {
  63336. var p = start;
  63337. do {
  63338. if (p.z === null)
  63339. p.z = zOrder(p.x, p.y, minX, minY, size);
  63340. p.prevZ = p.prev;
  63341. p.nextZ = p.next;
  63342. p = p.next;
  63343. } while (p !== start);
  63344. p.prevZ.nextZ = null;
  63345. p.prevZ = null;
  63346. sortLinked(p);
  63347. }
  63348. // Simon Tatham's linked list merge sort algorithm
  63349. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63350. function sortLinked(list) {
  63351. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63352. do {
  63353. p = list;
  63354. list = null;
  63355. tail = null;
  63356. numMerges = 0;
  63357. while (p) {
  63358. numMerges++;
  63359. q = p;
  63360. pSize = 0;
  63361. for (i = 0; i < inSize; i++) {
  63362. pSize++;
  63363. q = q.nextZ;
  63364. if (!q)
  63365. break;
  63366. }
  63367. qSize = inSize;
  63368. while (pSize > 0 || (qSize > 0 && q)) {
  63369. if (pSize === 0) {
  63370. e = q;
  63371. q = q.nextZ;
  63372. qSize--;
  63373. }
  63374. else if (qSize === 0 || !q) {
  63375. e = p;
  63376. p = p.nextZ;
  63377. pSize--;
  63378. }
  63379. else if (p.z <= q.z) {
  63380. e = p;
  63381. p = p.nextZ;
  63382. pSize--;
  63383. }
  63384. else {
  63385. e = q;
  63386. q = q.nextZ;
  63387. qSize--;
  63388. }
  63389. if (tail)
  63390. tail.nextZ = e;
  63391. else
  63392. list = e;
  63393. e.prevZ = tail;
  63394. tail = e;
  63395. }
  63396. p = q;
  63397. }
  63398. tail.nextZ = null;
  63399. inSize *= 2;
  63400. } while (numMerges > 1);
  63401. return list;
  63402. }
  63403. // z-order of a point given coords and size of the data bounding box
  63404. function zOrder(x, y, minX, minY, size) {
  63405. // coords are transformed into non-negative 15-bit integer range
  63406. x = 32767 * (x - minX) / size;
  63407. y = 32767 * (y - minY) / size;
  63408. x = (x | (x << 8)) & 0x00FF00FF;
  63409. x = (x | (x << 4)) & 0x0F0F0F0F;
  63410. x = (x | (x << 2)) & 0x33333333;
  63411. x = (x | (x << 1)) & 0x55555555;
  63412. y = (y | (y << 8)) & 0x00FF00FF;
  63413. y = (y | (y << 4)) & 0x0F0F0F0F;
  63414. y = (y | (y << 2)) & 0x33333333;
  63415. y = (y | (y << 1)) & 0x55555555;
  63416. return x | (y << 1);
  63417. }
  63418. // find the leftmost node of a polygon ring
  63419. function getLeftmost(start) {
  63420. var p = start, leftmost = start;
  63421. do {
  63422. if (p.x < leftmost.x)
  63423. leftmost = p;
  63424. p = p.next;
  63425. } while (p !== start);
  63426. return leftmost;
  63427. }
  63428. // check if a point lies within a convex triangle
  63429. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63430. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63431. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63432. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63433. }
  63434. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63435. function isValidDiagonal(a, b) {
  63436. return a.next.i !== b.i &&
  63437. a.prev.i !== b.i &&
  63438. !intersectsPolygon(a, b) &&
  63439. locallyInside(a, b) &&
  63440. locallyInside(b, a) &&
  63441. middleInside(a, b);
  63442. }
  63443. // signed area of a triangle
  63444. function area(p, q, r) {
  63445. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63446. }
  63447. // check if two points are equal
  63448. function equals(p1, p2) {
  63449. return p1.x === p2.x && p1.y === p2.y;
  63450. }
  63451. // check if two segments intersect
  63452. function intersects(p1, q1, p2, q2) {
  63453. if ((equals(p1, q1) && equals(p2, q2)) ||
  63454. (equals(p1, q2) && equals(p2, q1)))
  63455. return true;
  63456. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63457. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63458. }
  63459. // check if a polygon diagonal intersects any polygon segments
  63460. function intersectsPolygon(a, b) {
  63461. var p = a;
  63462. do {
  63463. if (p.i !== a.i &&
  63464. p.next.i !== a.i &&
  63465. p.i !== b.i &&
  63466. p.next.i !== b.i &&
  63467. intersects(p, p.next, a, b))
  63468. return true;
  63469. p = p.next;
  63470. } while (p !== a);
  63471. return false;
  63472. }
  63473. // check if a polygon diagonal is locally inside the polygon
  63474. function locallyInside(a, b) {
  63475. return area(a.prev, a, a.next) < 0
  63476. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63477. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63478. }
  63479. // check if the middle point of a polygon diagonal is inside the polygon
  63480. function middleInside(a, b) {
  63481. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63482. do {
  63483. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63484. inside = !inside;
  63485. p = p.next;
  63486. } while (p !== a);
  63487. return inside;
  63488. }
  63489. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63490. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63491. function splitPolygon(a, b) {
  63492. 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;
  63493. a.next = b;
  63494. b.prev = a;
  63495. a2.next = an;
  63496. an.prev = a2;
  63497. b2.next = a2;
  63498. a2.prev = b2;
  63499. bp.next = b2;
  63500. b2.prev = bp;
  63501. return b2;
  63502. }
  63503. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63504. function insertNode(i, x, y, last) {
  63505. var p = new Node(i, x, y);
  63506. if (!last) {
  63507. p.prev = p;
  63508. p.next = p;
  63509. }
  63510. else {
  63511. p.next = last.next;
  63512. p.prev = last;
  63513. last.next.prev = p;
  63514. last.next = p;
  63515. }
  63516. return p;
  63517. }
  63518. function removeNode(p) {
  63519. p.next.prev = p.prev;
  63520. p.prev.next = p.next;
  63521. if (p.prevZ)
  63522. p.prevZ.nextZ = p.nextZ;
  63523. if (p.nextZ)
  63524. p.nextZ.prevZ = p.prevZ;
  63525. }
  63526. /**
  63527. * return a percentage difference between the polygon area and its triangulation area;
  63528. * used to verify correctness of triangulation
  63529. */
  63530. function deviation(data, holeIndices, dim, triangles) {
  63531. var hasHoles = holeIndices && holeIndices.length;
  63532. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  63533. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  63534. if (hasHoles) {
  63535. for (var i = 0, len = holeIndices.length; i < len; i++) {
  63536. var start = holeIndices[i] * dim;
  63537. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63538. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  63539. }
  63540. }
  63541. var trianglesArea = 0;
  63542. for (i = 0; i < triangles.length; i += 3) {
  63543. var a = triangles[i] * dim;
  63544. var b = triangles[i + 1] * dim;
  63545. var c = triangles[i + 2] * dim;
  63546. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  63547. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  63548. }
  63549. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  63550. }
  63551. Earcut.deviation = deviation;
  63552. ;
  63553. function signedArea(data, start, end, dim) {
  63554. var sum = 0;
  63555. for (var i = start, j = end - dim; i < end; i += dim) {
  63556. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  63557. j = i;
  63558. }
  63559. return sum;
  63560. }
  63561. /**
  63562. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  63563. */
  63564. function flatten(data) {
  63565. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  63566. for (var i = 0; i < data.length; i++) {
  63567. for (var j = 0; j < data[i].length; j++) {
  63568. for (var d = 0; d < dim; d++)
  63569. result.vertices.push(data[i][j][d]);
  63570. }
  63571. if (i > 0) {
  63572. holeIndex += data[i - 1].length;
  63573. result.holes.push(holeIndex);
  63574. }
  63575. }
  63576. return result;
  63577. }
  63578. Earcut.flatten = flatten;
  63579. ;
  63580. })(Earcut || (Earcut = {}));
  63581. //# sourceMappingURL=babylon.earcut.js.map
  63582. /// <reference path="..\Math\babylon.math.ts" />
  63583. var BABYLON;
  63584. (function (BABYLON) {
  63585. var IndexedVector2 = /** @class */ (function (_super) {
  63586. __extends(IndexedVector2, _super);
  63587. function IndexedVector2(original, index) {
  63588. var _this = _super.call(this, original.x, original.y) || this;
  63589. _this.index = index;
  63590. return _this;
  63591. }
  63592. return IndexedVector2;
  63593. }(BABYLON.Vector2));
  63594. var PolygonPoints = /** @class */ (function () {
  63595. function PolygonPoints() {
  63596. this.elements = new Array();
  63597. }
  63598. PolygonPoints.prototype.add = function (originalPoints) {
  63599. var _this = this;
  63600. var result = new Array();
  63601. originalPoints.forEach(function (point) {
  63602. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  63603. var newPoint = new IndexedVector2(point, _this.elements.length);
  63604. result.push(newPoint);
  63605. _this.elements.push(newPoint);
  63606. }
  63607. });
  63608. return result;
  63609. };
  63610. PolygonPoints.prototype.computeBounds = function () {
  63611. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63612. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63613. this.elements.forEach(function (point) {
  63614. // x
  63615. if (point.x < lmin.x) {
  63616. lmin.x = point.x;
  63617. }
  63618. else if (point.x > lmax.x) {
  63619. lmax.x = point.x;
  63620. }
  63621. // y
  63622. if (point.y < lmin.y) {
  63623. lmin.y = point.y;
  63624. }
  63625. else if (point.y > lmax.y) {
  63626. lmax.y = point.y;
  63627. }
  63628. });
  63629. return {
  63630. min: lmin,
  63631. max: lmax,
  63632. width: lmax.x - lmin.x,
  63633. height: lmax.y - lmin.y
  63634. };
  63635. };
  63636. return PolygonPoints;
  63637. }());
  63638. var Polygon = /** @class */ (function () {
  63639. function Polygon() {
  63640. }
  63641. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  63642. return [
  63643. new BABYLON.Vector2(xmin, ymin),
  63644. new BABYLON.Vector2(xmax, ymin),
  63645. new BABYLON.Vector2(xmax, ymax),
  63646. new BABYLON.Vector2(xmin, ymax)
  63647. ];
  63648. };
  63649. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  63650. if (cx === void 0) { cx = 0; }
  63651. if (cy === void 0) { cy = 0; }
  63652. if (numberOfSides === void 0) { numberOfSides = 32; }
  63653. var result = new Array();
  63654. var angle = 0;
  63655. var increment = (Math.PI * 2) / numberOfSides;
  63656. for (var i = 0; i < numberOfSides; i++) {
  63657. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  63658. angle -= increment;
  63659. }
  63660. return result;
  63661. };
  63662. Polygon.Parse = function (input) {
  63663. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  63664. var i, result = [];
  63665. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  63666. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  63667. }
  63668. return result;
  63669. };
  63670. Polygon.StartingAt = function (x, y) {
  63671. return BABYLON.Path2.StartingAt(x, y);
  63672. };
  63673. return Polygon;
  63674. }());
  63675. BABYLON.Polygon = Polygon;
  63676. var PolygonMeshBuilder = /** @class */ (function () {
  63677. function PolygonMeshBuilder(name, contours, scene) {
  63678. this._points = new PolygonPoints();
  63679. this._outlinepoints = new PolygonPoints();
  63680. this._holes = new Array();
  63681. this._epoints = new Array();
  63682. this._eholes = new Array();
  63683. this._name = name;
  63684. this._scene = scene;
  63685. var points;
  63686. if (contours instanceof BABYLON.Path2) {
  63687. points = contours.getPoints();
  63688. }
  63689. else {
  63690. points = contours;
  63691. }
  63692. this._addToepoint(points);
  63693. this._points.add(points);
  63694. this._outlinepoints.add(points);
  63695. }
  63696. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  63697. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  63698. var p = points_1[_i];
  63699. this._epoints.push(p.x, p.y);
  63700. }
  63701. };
  63702. PolygonMeshBuilder.prototype.addHole = function (hole) {
  63703. this._points.add(hole);
  63704. var holepoints = new PolygonPoints();
  63705. holepoints.add(hole);
  63706. this._holes.push(holepoints);
  63707. this._eholes.push(this._epoints.length / 2);
  63708. this._addToepoint(hole);
  63709. return this;
  63710. };
  63711. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  63712. var _this = this;
  63713. if (updatable === void 0) { updatable = false; }
  63714. if (depth === void 0) { depth = 0; }
  63715. var result = new BABYLON.Mesh(this._name, this._scene);
  63716. var normals = new Array();
  63717. var positions = new Array();
  63718. var uvs = new Array();
  63719. var bounds = this._points.computeBounds();
  63720. this._points.elements.forEach(function (p) {
  63721. normals.push(0, 1.0, 0);
  63722. positions.push(p.x, 0, p.y);
  63723. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  63724. });
  63725. var indices = new Array();
  63726. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  63727. for (var i = 0; i < res.length; i++) {
  63728. indices.push(res[i]);
  63729. }
  63730. if (depth > 0) {
  63731. var positionscount = (positions.length / 3); //get the current pointcount
  63732. this._points.elements.forEach(function (p) {
  63733. normals.push(0, -1.0, 0);
  63734. positions.push(p.x, -depth, p.y);
  63735. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  63736. });
  63737. var totalCount = indices.length;
  63738. for (var i = 0; i < totalCount; i += 3) {
  63739. var i0 = indices[i + 0];
  63740. var i1 = indices[i + 1];
  63741. var i2 = indices[i + 2];
  63742. indices.push(i2 + positionscount);
  63743. indices.push(i1 + positionscount);
  63744. indices.push(i0 + positionscount);
  63745. }
  63746. //Add the sides
  63747. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  63748. this._holes.forEach(function (hole) {
  63749. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  63750. });
  63751. }
  63752. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  63753. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  63754. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  63755. result.setIndices(indices);
  63756. return result;
  63757. };
  63758. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  63759. var StartIndex = positions.length / 3;
  63760. var ulength = 0;
  63761. for (var i = 0; i < points.elements.length; i++) {
  63762. var p = points.elements[i];
  63763. var p1;
  63764. if ((i + 1) > points.elements.length - 1) {
  63765. p1 = points.elements[0];
  63766. }
  63767. else {
  63768. p1 = points.elements[i + 1];
  63769. }
  63770. positions.push(p.x, 0, p.y);
  63771. positions.push(p.x, -depth, p.y);
  63772. positions.push(p1.x, 0, p1.y);
  63773. positions.push(p1.x, -depth, p1.y);
  63774. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  63775. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  63776. var v3 = v2.subtract(v1);
  63777. var v4 = new BABYLON.Vector3(0, 1, 0);
  63778. var vn = BABYLON.Vector3.Cross(v3, v4);
  63779. vn = vn.normalize();
  63780. uvs.push(ulength / bounds.width, 0);
  63781. uvs.push(ulength / bounds.width, 1);
  63782. ulength += v3.length();
  63783. uvs.push((ulength / bounds.width), 0);
  63784. uvs.push((ulength / bounds.width), 1);
  63785. if (!flip) {
  63786. normals.push(-vn.x, -vn.y, -vn.z);
  63787. normals.push(-vn.x, -vn.y, -vn.z);
  63788. normals.push(-vn.x, -vn.y, -vn.z);
  63789. normals.push(-vn.x, -vn.y, -vn.z);
  63790. indices.push(StartIndex);
  63791. indices.push(StartIndex + 1);
  63792. indices.push(StartIndex + 2);
  63793. indices.push(StartIndex + 1);
  63794. indices.push(StartIndex + 3);
  63795. indices.push(StartIndex + 2);
  63796. }
  63797. else {
  63798. normals.push(vn.x, vn.y, vn.z);
  63799. normals.push(vn.x, vn.y, vn.z);
  63800. normals.push(vn.x, vn.y, vn.z);
  63801. normals.push(vn.x, vn.y, vn.z);
  63802. indices.push(StartIndex);
  63803. indices.push(StartIndex + 2);
  63804. indices.push(StartIndex + 1);
  63805. indices.push(StartIndex + 1);
  63806. indices.push(StartIndex + 2);
  63807. indices.push(StartIndex + 3);
  63808. }
  63809. StartIndex += 4;
  63810. }
  63811. ;
  63812. };
  63813. return PolygonMeshBuilder;
  63814. }());
  63815. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  63816. })(BABYLON || (BABYLON = {}));
  63817. //# sourceMappingURL=babylon.polygonMesh.js.map
  63818. var BABYLON;
  63819. (function (BABYLON) {
  63820. // Unique ID when we import meshes from Babylon to CSG
  63821. var currentCSGMeshId = 0;
  63822. // # class Vertex
  63823. // Represents a vertex of a polygon. Use your own vertex class instead of this
  63824. // one to provide additional features like texture coordinates and vertex
  63825. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  63826. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  63827. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  63828. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  63829. // is not used anywhere else.
  63830. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  63831. var Vertex = /** @class */ (function () {
  63832. function Vertex(pos, normal, uv) {
  63833. this.pos = pos;
  63834. this.normal = normal;
  63835. this.uv = uv;
  63836. }
  63837. Vertex.prototype.clone = function () {
  63838. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  63839. };
  63840. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  63841. // orientation of a polygon is flipped.
  63842. Vertex.prototype.flip = function () {
  63843. this.normal = this.normal.scale(-1);
  63844. };
  63845. // Create a new vertex between this vertex and `other` by linearly
  63846. // interpolating all properties using a parameter of `t`. Subclasses should
  63847. // override this to interpolate additional properties.
  63848. Vertex.prototype.interpolate = function (other, t) {
  63849. 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));
  63850. };
  63851. return Vertex;
  63852. }());
  63853. // # class Plane
  63854. // Represents a plane in 3D space.
  63855. var Plane = /** @class */ (function () {
  63856. function Plane(normal, w) {
  63857. this.normal = normal;
  63858. this.w = w;
  63859. }
  63860. Plane.FromPoints = function (a, b, c) {
  63861. var v0 = c.subtract(a);
  63862. var v1 = b.subtract(a);
  63863. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  63864. return null;
  63865. }
  63866. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  63867. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  63868. };
  63869. Plane.prototype.clone = function () {
  63870. return new Plane(this.normal.clone(), this.w);
  63871. };
  63872. Plane.prototype.flip = function () {
  63873. this.normal.scaleInPlace(-1);
  63874. this.w = -this.w;
  63875. };
  63876. // Split `polygon` by this plane if needed, then put the polygon or polygon
  63877. // fragments in the appropriate lists. Coplanar polygons go into either
  63878. // `coplanarFront` or `coplanarBack` depending on their orientation with
  63879. // respect to this plane. Polygons in front or in back of this plane go into
  63880. // either `front` or `back`.
  63881. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  63882. var COPLANAR = 0;
  63883. var FRONT = 1;
  63884. var BACK = 2;
  63885. var SPANNING = 3;
  63886. // Classify each point as well as the entire polygon into one of the above
  63887. // four classes.
  63888. var polygonType = 0;
  63889. var types = [];
  63890. var i;
  63891. var t;
  63892. for (i = 0; i < polygon.vertices.length; i++) {
  63893. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  63894. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  63895. polygonType |= type;
  63896. types.push(type);
  63897. }
  63898. // Put the polygon in the correct list, splitting it when necessary.
  63899. switch (polygonType) {
  63900. case COPLANAR:
  63901. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  63902. break;
  63903. case FRONT:
  63904. front.push(polygon);
  63905. break;
  63906. case BACK:
  63907. back.push(polygon);
  63908. break;
  63909. case SPANNING:
  63910. var f = [], b = [];
  63911. for (i = 0; i < polygon.vertices.length; i++) {
  63912. var j = (i + 1) % polygon.vertices.length;
  63913. var ti = types[i], tj = types[j];
  63914. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  63915. if (ti !== BACK)
  63916. f.push(vi);
  63917. if (ti !== FRONT)
  63918. b.push(ti !== BACK ? vi.clone() : vi);
  63919. if ((ti | tj) === SPANNING) {
  63920. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  63921. var v = vi.interpolate(vj, t);
  63922. f.push(v);
  63923. b.push(v.clone());
  63924. }
  63925. }
  63926. var poly;
  63927. if (f.length >= 3) {
  63928. poly = new Polygon(f, polygon.shared);
  63929. if (poly.plane)
  63930. front.push(poly);
  63931. }
  63932. if (b.length >= 3) {
  63933. poly = new Polygon(b, polygon.shared);
  63934. if (poly.plane)
  63935. back.push(poly);
  63936. }
  63937. break;
  63938. }
  63939. };
  63940. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  63941. // point is on the plane.
  63942. Plane.EPSILON = 1e-5;
  63943. return Plane;
  63944. }());
  63945. // # class Polygon
  63946. // Represents a convex polygon. The vertices used to initialize a polygon must
  63947. // be coplanar and form a convex loop.
  63948. //
  63949. // Each convex polygon has a `shared` property, which is shared between all
  63950. // polygons that are clones of each other or were split from the same polygon.
  63951. // This can be used to define per-polygon properties (such as surface color).
  63952. var Polygon = /** @class */ (function () {
  63953. function Polygon(vertices, shared) {
  63954. this.vertices = vertices;
  63955. this.shared = shared;
  63956. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  63957. }
  63958. Polygon.prototype.clone = function () {
  63959. var vertices = this.vertices.map(function (v) { return v.clone(); });
  63960. return new Polygon(vertices, this.shared);
  63961. };
  63962. Polygon.prototype.flip = function () {
  63963. this.vertices.reverse().map(function (v) { v.flip(); });
  63964. this.plane.flip();
  63965. };
  63966. return Polygon;
  63967. }());
  63968. // # class Node
  63969. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  63970. // by picking a polygon to split along. That polygon (and all other coplanar
  63971. // polygons) are added directly to that node and the other polygons are added to
  63972. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  63973. // no distinction between internal and leaf nodes.
  63974. var Node = /** @class */ (function () {
  63975. function Node(polygons) {
  63976. this.plane = null;
  63977. this.front = null;
  63978. this.back = null;
  63979. this.polygons = new Array();
  63980. if (polygons) {
  63981. this.build(polygons);
  63982. }
  63983. }
  63984. Node.prototype.clone = function () {
  63985. var node = new Node();
  63986. node.plane = this.plane && this.plane.clone();
  63987. node.front = this.front && this.front.clone();
  63988. node.back = this.back && this.back.clone();
  63989. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  63990. return node;
  63991. };
  63992. // Convert solid space to empty space and empty space to solid space.
  63993. Node.prototype.invert = function () {
  63994. for (var i = 0; i < this.polygons.length; i++) {
  63995. this.polygons[i].flip();
  63996. }
  63997. if (this.plane) {
  63998. this.plane.flip();
  63999. }
  64000. if (this.front) {
  64001. this.front.invert();
  64002. }
  64003. if (this.back) {
  64004. this.back.invert();
  64005. }
  64006. var temp = this.front;
  64007. this.front = this.back;
  64008. this.back = temp;
  64009. };
  64010. // Recursively remove all polygons in `polygons` that are inside this BSP
  64011. // tree.
  64012. Node.prototype.clipPolygons = function (polygons) {
  64013. if (!this.plane)
  64014. return polygons.slice();
  64015. var front = new Array(), back = new Array();
  64016. for (var i = 0; i < polygons.length; i++) {
  64017. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64018. }
  64019. if (this.front) {
  64020. front = this.front.clipPolygons(front);
  64021. }
  64022. if (this.back) {
  64023. back = this.back.clipPolygons(back);
  64024. }
  64025. else {
  64026. back = [];
  64027. }
  64028. return front.concat(back);
  64029. };
  64030. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64031. // `bsp`.
  64032. Node.prototype.clipTo = function (bsp) {
  64033. this.polygons = bsp.clipPolygons(this.polygons);
  64034. if (this.front)
  64035. this.front.clipTo(bsp);
  64036. if (this.back)
  64037. this.back.clipTo(bsp);
  64038. };
  64039. // Return a list of all polygons in this BSP tree.
  64040. Node.prototype.allPolygons = function () {
  64041. var polygons = this.polygons.slice();
  64042. if (this.front)
  64043. polygons = polygons.concat(this.front.allPolygons());
  64044. if (this.back)
  64045. polygons = polygons.concat(this.back.allPolygons());
  64046. return polygons;
  64047. };
  64048. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64049. // new polygons are filtered down to the bottom of the tree and become new
  64050. // nodes there. Each set of polygons is partitioned using the first polygon
  64051. // (no heuristic is used to pick a good split).
  64052. Node.prototype.build = function (polygons) {
  64053. if (!polygons.length)
  64054. return;
  64055. if (!this.plane)
  64056. this.plane = polygons[0].plane.clone();
  64057. var front = new Array(), back = new Array();
  64058. for (var i = 0; i < polygons.length; i++) {
  64059. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64060. }
  64061. if (front.length) {
  64062. if (!this.front)
  64063. this.front = new Node();
  64064. this.front.build(front);
  64065. }
  64066. if (back.length) {
  64067. if (!this.back)
  64068. this.back = new Node();
  64069. this.back.build(back);
  64070. }
  64071. };
  64072. return Node;
  64073. }());
  64074. var CSG = /** @class */ (function () {
  64075. function CSG() {
  64076. this.polygons = new Array();
  64077. }
  64078. // Convert BABYLON.Mesh to BABYLON.CSG
  64079. CSG.FromMesh = function (mesh) {
  64080. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64081. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64082. if (mesh instanceof BABYLON.Mesh) {
  64083. mesh.computeWorldMatrix(true);
  64084. matrix = mesh.getWorldMatrix();
  64085. meshPosition = mesh.position.clone();
  64086. meshRotation = mesh.rotation.clone();
  64087. if (mesh.rotationQuaternion) {
  64088. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64089. }
  64090. meshScaling = mesh.scaling.clone();
  64091. }
  64092. else {
  64093. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64094. }
  64095. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64096. var subMeshes = mesh.subMeshes;
  64097. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64098. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64099. vertices = [];
  64100. for (var j = 0; j < 3; j++) {
  64101. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64102. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64103. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64104. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64105. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64106. vertex = new Vertex(position, normal, uv);
  64107. vertices.push(vertex);
  64108. }
  64109. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64110. // To handle the case of degenerated triangle
  64111. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64112. if (polygon.plane)
  64113. polygons.push(polygon);
  64114. }
  64115. }
  64116. var csg = CSG.FromPolygons(polygons);
  64117. csg.matrix = matrix;
  64118. csg.position = meshPosition;
  64119. csg.rotation = meshRotation;
  64120. csg.scaling = meshScaling;
  64121. csg.rotationQuaternion = meshRotationQuaternion;
  64122. currentCSGMeshId++;
  64123. return csg;
  64124. };
  64125. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64126. CSG.FromPolygons = function (polygons) {
  64127. var csg = new CSG();
  64128. csg.polygons = polygons;
  64129. return csg;
  64130. };
  64131. CSG.prototype.clone = function () {
  64132. var csg = new CSG();
  64133. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64134. csg.copyTransformAttributes(this);
  64135. return csg;
  64136. };
  64137. CSG.prototype.union = function (csg) {
  64138. var a = new Node(this.clone().polygons);
  64139. var b = new Node(csg.clone().polygons);
  64140. a.clipTo(b);
  64141. b.clipTo(a);
  64142. b.invert();
  64143. b.clipTo(a);
  64144. b.invert();
  64145. a.build(b.allPolygons());
  64146. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64147. };
  64148. CSG.prototype.unionInPlace = function (csg) {
  64149. var a = new Node(this.polygons);
  64150. var b = new Node(csg.polygons);
  64151. a.clipTo(b);
  64152. b.clipTo(a);
  64153. b.invert();
  64154. b.clipTo(a);
  64155. b.invert();
  64156. a.build(b.allPolygons());
  64157. this.polygons = a.allPolygons();
  64158. };
  64159. CSG.prototype.subtract = function (csg) {
  64160. var a = new Node(this.clone().polygons);
  64161. var b = new Node(csg.clone().polygons);
  64162. a.invert();
  64163. a.clipTo(b);
  64164. b.clipTo(a);
  64165. b.invert();
  64166. b.clipTo(a);
  64167. b.invert();
  64168. a.build(b.allPolygons());
  64169. a.invert();
  64170. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64171. };
  64172. CSG.prototype.subtractInPlace = function (csg) {
  64173. var a = new Node(this.polygons);
  64174. var b = new Node(csg.polygons);
  64175. a.invert();
  64176. a.clipTo(b);
  64177. b.clipTo(a);
  64178. b.invert();
  64179. b.clipTo(a);
  64180. b.invert();
  64181. a.build(b.allPolygons());
  64182. a.invert();
  64183. this.polygons = a.allPolygons();
  64184. };
  64185. CSG.prototype.intersect = function (csg) {
  64186. var a = new Node(this.clone().polygons);
  64187. var b = new Node(csg.clone().polygons);
  64188. a.invert();
  64189. b.clipTo(a);
  64190. b.invert();
  64191. a.clipTo(b);
  64192. b.clipTo(a);
  64193. a.build(b.allPolygons());
  64194. a.invert();
  64195. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64196. };
  64197. CSG.prototype.intersectInPlace = function (csg) {
  64198. var a = new Node(this.polygons);
  64199. var b = new Node(csg.polygons);
  64200. a.invert();
  64201. b.clipTo(a);
  64202. b.invert();
  64203. a.clipTo(b);
  64204. b.clipTo(a);
  64205. a.build(b.allPolygons());
  64206. a.invert();
  64207. this.polygons = a.allPolygons();
  64208. };
  64209. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64210. // not modified.
  64211. CSG.prototype.inverse = function () {
  64212. var csg = this.clone();
  64213. csg.inverseInPlace();
  64214. return csg;
  64215. };
  64216. CSG.prototype.inverseInPlace = function () {
  64217. this.polygons.map(function (p) { p.flip(); });
  64218. };
  64219. // This is used to keep meshes transformations so they can be restored
  64220. // when we build back a Babylon Mesh
  64221. // NB : All CSG operations are performed in world coordinates
  64222. CSG.prototype.copyTransformAttributes = function (csg) {
  64223. this.matrix = csg.matrix;
  64224. this.position = csg.position;
  64225. this.rotation = csg.rotation;
  64226. this.scaling = csg.scaling;
  64227. this.rotationQuaternion = csg.rotationQuaternion;
  64228. return this;
  64229. };
  64230. // Build Raw mesh from CSG
  64231. // Coordinates here are in world space
  64232. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64233. var matrix = this.matrix.clone();
  64234. matrix.invert();
  64235. 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;
  64236. if (keepSubMeshes) {
  64237. // Sort Polygons, since subMeshes are indices range
  64238. polygons.sort(function (a, b) {
  64239. if (a.shared.meshId === b.shared.meshId) {
  64240. return a.shared.subMeshId - b.shared.subMeshId;
  64241. }
  64242. else {
  64243. return a.shared.meshId - b.shared.meshId;
  64244. }
  64245. });
  64246. }
  64247. for (var i = 0, il = polygons.length; i < il; i++) {
  64248. polygon = polygons[i];
  64249. // Building SubMeshes
  64250. if (!subMesh_dict[polygon.shared.meshId]) {
  64251. subMesh_dict[polygon.shared.meshId] = {};
  64252. }
  64253. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64254. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64255. indexStart: +Infinity,
  64256. indexEnd: -Infinity,
  64257. materialIndex: polygon.shared.materialIndex
  64258. };
  64259. }
  64260. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64261. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64262. polygonIndices[0] = 0;
  64263. polygonIndices[1] = j - 1;
  64264. polygonIndices[2] = j;
  64265. for (var k = 0; k < 3; k++) {
  64266. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64267. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64268. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64269. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64270. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64271. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64272. // Check if 2 points can be merged
  64273. if (!(typeof vertex_idx !== 'undefined' &&
  64274. normals[vertex_idx * 3] === localNormal.x &&
  64275. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64276. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64277. uvs[vertex_idx * 2] === uv.x &&
  64278. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64279. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64280. uvs.push(uv.x, uv.y);
  64281. normals.push(normal.x, normal.y, normal.z);
  64282. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64283. }
  64284. indices.push(vertex_idx);
  64285. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64286. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64287. currentIndex++;
  64288. }
  64289. }
  64290. }
  64291. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64292. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64293. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64294. mesh.setIndices(indices, null);
  64295. if (keepSubMeshes) {
  64296. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64297. var materialIndexOffset = 0, materialMaxIndex;
  64298. mesh.subMeshes = new Array();
  64299. for (var m in subMesh_dict) {
  64300. materialMaxIndex = -1;
  64301. for (var sm in subMesh_dict[m]) {
  64302. subMesh_obj = subMesh_dict[m][sm];
  64303. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64304. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64305. }
  64306. materialIndexOffset += ++materialMaxIndex;
  64307. }
  64308. }
  64309. return mesh;
  64310. };
  64311. // Build Mesh from CSG taking material and transforms into account
  64312. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64313. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64314. mesh.material = material;
  64315. mesh.position.copyFrom(this.position);
  64316. mesh.rotation.copyFrom(this.rotation);
  64317. if (this.rotationQuaternion) {
  64318. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64319. }
  64320. mesh.scaling.copyFrom(this.scaling);
  64321. mesh.computeWorldMatrix(true);
  64322. return mesh;
  64323. };
  64324. return CSG;
  64325. }());
  64326. BABYLON.CSG = CSG;
  64327. })(BABYLON || (BABYLON = {}));
  64328. //# sourceMappingURL=babylon.csg.js.map
  64329. var BABYLON;
  64330. (function (BABYLON) {
  64331. var LensFlare = /** @class */ (function () {
  64332. function LensFlare(size, position, color, imgUrl, system) {
  64333. this.size = size;
  64334. this.position = position;
  64335. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64336. this.color = color || new BABYLON.Color3(1, 1, 1);
  64337. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64338. this._system = system;
  64339. system.lensFlares.push(this);
  64340. }
  64341. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64342. return new LensFlare(size, position, color, imgUrl, system);
  64343. };
  64344. LensFlare.prototype.dispose = function () {
  64345. if (this.texture) {
  64346. this.texture.dispose();
  64347. }
  64348. // Remove from scene
  64349. var index = this._system.lensFlares.indexOf(this);
  64350. this._system.lensFlares.splice(index, 1);
  64351. };
  64352. ;
  64353. return LensFlare;
  64354. }());
  64355. BABYLON.LensFlare = LensFlare;
  64356. })(BABYLON || (BABYLON = {}));
  64357. //# sourceMappingURL=babylon.lensFlare.js.map
  64358. var BABYLON;
  64359. (function (BABYLON) {
  64360. var LensFlareSystem = /** @class */ (function () {
  64361. function LensFlareSystem(name, emitter, scene) {
  64362. this.name = name;
  64363. this.lensFlares = new Array();
  64364. this.borderLimit = 300;
  64365. this.viewportBorder = 0;
  64366. this.layerMask = 0x0FFFFFFF;
  64367. this._vertexBuffers = {};
  64368. this._isEnabled = true;
  64369. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64370. this._emitter = emitter;
  64371. this.id = name;
  64372. scene.lensFlareSystems.push(this);
  64373. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64374. var engine = scene.getEngine();
  64375. // VBO
  64376. var vertices = [];
  64377. vertices.push(1, 1);
  64378. vertices.push(-1, 1);
  64379. vertices.push(-1, -1);
  64380. vertices.push(1, -1);
  64381. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64382. // Indices
  64383. var indices = [];
  64384. indices.push(0);
  64385. indices.push(1);
  64386. indices.push(2);
  64387. indices.push(0);
  64388. indices.push(2);
  64389. indices.push(3);
  64390. this._indexBuffer = engine.createIndexBuffer(indices);
  64391. // Effects
  64392. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64393. }
  64394. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64395. get: function () {
  64396. return this._isEnabled;
  64397. },
  64398. set: function (value) {
  64399. this._isEnabled = value;
  64400. },
  64401. enumerable: true,
  64402. configurable: true
  64403. });
  64404. LensFlareSystem.prototype.getScene = function () {
  64405. return this._scene;
  64406. };
  64407. LensFlareSystem.prototype.getEmitter = function () {
  64408. return this._emitter;
  64409. };
  64410. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64411. this._emitter = newEmitter;
  64412. };
  64413. LensFlareSystem.prototype.getEmitterPosition = function () {
  64414. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64415. };
  64416. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64417. var position = this.getEmitterPosition();
  64418. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64419. this._positionX = position.x;
  64420. this._positionY = position.y;
  64421. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64422. if (this.viewportBorder > 0) {
  64423. globalViewport.x -= this.viewportBorder;
  64424. globalViewport.y -= this.viewportBorder;
  64425. globalViewport.width += this.viewportBorder * 2;
  64426. globalViewport.height += this.viewportBorder * 2;
  64427. position.x += this.viewportBorder;
  64428. position.y += this.viewportBorder;
  64429. this._positionX += this.viewportBorder;
  64430. this._positionY += this.viewportBorder;
  64431. }
  64432. if (position.z > 0) {
  64433. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64434. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64435. return true;
  64436. }
  64437. return true;
  64438. }
  64439. return false;
  64440. };
  64441. LensFlareSystem.prototype._isVisible = function () {
  64442. if (!this._isEnabled || !this._scene.activeCamera) {
  64443. return false;
  64444. }
  64445. var emitterPosition = this.getEmitterPosition();
  64446. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64447. var distance = direction.length();
  64448. direction.normalize();
  64449. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64450. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64451. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64452. };
  64453. LensFlareSystem.prototype.render = function () {
  64454. if (!this._effect.isReady() || !this._scene.activeCamera)
  64455. return false;
  64456. var engine = this._scene.getEngine();
  64457. var viewport = this._scene.activeCamera.viewport;
  64458. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64459. // Position
  64460. if (!this.computeEffectivePosition(globalViewport)) {
  64461. return false;
  64462. }
  64463. // Visibility
  64464. if (!this._isVisible()) {
  64465. return false;
  64466. }
  64467. // Intensity
  64468. var awayX;
  64469. var awayY;
  64470. if (this._positionX < this.borderLimit + globalViewport.x) {
  64471. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64472. }
  64473. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64474. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64475. }
  64476. else {
  64477. awayX = 0;
  64478. }
  64479. if (this._positionY < this.borderLimit + globalViewport.y) {
  64480. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64481. }
  64482. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64483. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64484. }
  64485. else {
  64486. awayY = 0;
  64487. }
  64488. var away = (awayX > awayY) ? awayX : awayY;
  64489. away -= this.viewportBorder;
  64490. if (away > this.borderLimit) {
  64491. away = this.borderLimit;
  64492. }
  64493. var intensity = 1.0 - (away / this.borderLimit);
  64494. if (intensity < 0) {
  64495. return false;
  64496. }
  64497. if (intensity > 1.0) {
  64498. intensity = 1.0;
  64499. }
  64500. if (this.viewportBorder > 0) {
  64501. globalViewport.x += this.viewportBorder;
  64502. globalViewport.y += this.viewportBorder;
  64503. globalViewport.width -= this.viewportBorder * 2;
  64504. globalViewport.height -= this.viewportBorder * 2;
  64505. this._positionX -= this.viewportBorder;
  64506. this._positionY -= this.viewportBorder;
  64507. }
  64508. // Position
  64509. var centerX = globalViewport.x + globalViewport.width / 2;
  64510. var centerY = globalViewport.y + globalViewport.height / 2;
  64511. var distX = centerX - this._positionX;
  64512. var distY = centerY - this._positionY;
  64513. // Effects
  64514. engine.enableEffect(this._effect);
  64515. engine.setState(false);
  64516. engine.setDepthBuffer(false);
  64517. // VBOs
  64518. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64519. // Flares
  64520. for (var index = 0; index < this.lensFlares.length; index++) {
  64521. var flare = this.lensFlares[index];
  64522. engine.setAlphaMode(flare.alphaMode);
  64523. var x = centerX - (distX * flare.position);
  64524. var y = centerY - (distY * flare.position);
  64525. var cw = flare.size;
  64526. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  64527. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  64528. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  64529. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  64530. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  64531. // Texture
  64532. this._effect.setTexture("textureSampler", flare.texture);
  64533. // Color
  64534. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  64535. // Draw order
  64536. engine.draw(true, 0, 6);
  64537. }
  64538. engine.setDepthBuffer(true);
  64539. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64540. return true;
  64541. };
  64542. LensFlareSystem.prototype.dispose = function () {
  64543. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64544. if (vertexBuffer) {
  64545. vertexBuffer.dispose();
  64546. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64547. }
  64548. if (this._indexBuffer) {
  64549. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64550. this._indexBuffer = null;
  64551. }
  64552. while (this.lensFlares.length) {
  64553. this.lensFlares[0].dispose();
  64554. }
  64555. // Remove from scene
  64556. var index = this._scene.lensFlareSystems.indexOf(this);
  64557. this._scene.lensFlareSystems.splice(index, 1);
  64558. };
  64559. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  64560. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  64561. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  64562. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  64563. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  64564. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  64565. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  64566. var parsedFlare = parsedLensFlareSystem.flares[index];
  64567. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  64568. }
  64569. return lensFlareSystem;
  64570. };
  64571. LensFlareSystem.prototype.serialize = function () {
  64572. var serializationObject = {};
  64573. serializationObject.id = this.id;
  64574. serializationObject.name = this.name;
  64575. serializationObject.emitterId = this.getEmitter().id;
  64576. serializationObject.borderLimit = this.borderLimit;
  64577. serializationObject.flares = [];
  64578. for (var index = 0; index < this.lensFlares.length; index++) {
  64579. var flare = this.lensFlares[index];
  64580. serializationObject.flares.push({
  64581. size: flare.size,
  64582. position: flare.position,
  64583. color: flare.color.asArray(),
  64584. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  64585. });
  64586. }
  64587. return serializationObject;
  64588. };
  64589. return LensFlareSystem;
  64590. }());
  64591. BABYLON.LensFlareSystem = LensFlareSystem;
  64592. })(BABYLON || (BABYLON = {}));
  64593. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  64594. var BABYLON;
  64595. (function (BABYLON) {
  64596. /**
  64597. * This is a holder class for the physics joint created by the physics plugin.
  64598. * It holds a set of functions to control the underlying joint.
  64599. */
  64600. var PhysicsJoint = /** @class */ (function () {
  64601. function PhysicsJoint(type, jointData) {
  64602. this.type = type;
  64603. this.jointData = jointData;
  64604. jointData.nativeParams = jointData.nativeParams || {};
  64605. }
  64606. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  64607. get: function () {
  64608. return this._physicsJoint;
  64609. },
  64610. set: function (newJoint) {
  64611. if (this._physicsJoint) {
  64612. //remove from the wolrd
  64613. }
  64614. this._physicsJoint = newJoint;
  64615. },
  64616. enumerable: true,
  64617. configurable: true
  64618. });
  64619. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  64620. set: function (physicsPlugin) {
  64621. this._physicsPlugin = physicsPlugin;
  64622. },
  64623. enumerable: true,
  64624. configurable: true
  64625. });
  64626. /**
  64627. * Execute a function that is physics-plugin specific.
  64628. * @param {Function} func the function that will be executed.
  64629. * It accepts two parameters: the physics world and the physics joint.
  64630. */
  64631. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  64632. func(this._physicsPlugin.world, this._physicsJoint);
  64633. };
  64634. //TODO check if the native joints are the same
  64635. //Joint Types
  64636. PhysicsJoint.DistanceJoint = 0;
  64637. PhysicsJoint.HingeJoint = 1;
  64638. PhysicsJoint.BallAndSocketJoint = 2;
  64639. PhysicsJoint.WheelJoint = 3;
  64640. PhysicsJoint.SliderJoint = 4;
  64641. //OIMO
  64642. PhysicsJoint.PrismaticJoint = 5;
  64643. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  64644. PhysicsJoint.UniversalJoint = 6;
  64645. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  64646. //Cannon
  64647. //Similar to a Ball-Joint. Different in params
  64648. PhysicsJoint.PointToPointJoint = 8;
  64649. //Cannon only at the moment
  64650. PhysicsJoint.SpringJoint = 9;
  64651. PhysicsJoint.LockJoint = 10;
  64652. return PhysicsJoint;
  64653. }());
  64654. BABYLON.PhysicsJoint = PhysicsJoint;
  64655. /**
  64656. * A class representing a physics distance joint.
  64657. */
  64658. var DistanceJoint = /** @class */ (function (_super) {
  64659. __extends(DistanceJoint, _super);
  64660. function DistanceJoint(jointData) {
  64661. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  64662. }
  64663. /**
  64664. * Update the predefined distance.
  64665. */
  64666. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  64667. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  64668. };
  64669. return DistanceJoint;
  64670. }(PhysicsJoint));
  64671. BABYLON.DistanceJoint = DistanceJoint;
  64672. var MotorEnabledJoint = /** @class */ (function (_super) {
  64673. __extends(MotorEnabledJoint, _super);
  64674. function MotorEnabledJoint(type, jointData) {
  64675. return _super.call(this, type, jointData) || this;
  64676. }
  64677. /**
  64678. * Set the motor values.
  64679. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64680. * @param {number} force the force to apply
  64681. * @param {number} maxForce max force for this motor.
  64682. */
  64683. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  64684. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64685. };
  64686. /**
  64687. * Set the motor's limits.
  64688. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64689. */
  64690. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64691. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64692. };
  64693. return MotorEnabledJoint;
  64694. }(PhysicsJoint));
  64695. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  64696. /**
  64697. * This class represents a single hinge physics joint
  64698. */
  64699. var HingeJoint = /** @class */ (function (_super) {
  64700. __extends(HingeJoint, _super);
  64701. function HingeJoint(jointData) {
  64702. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  64703. }
  64704. /**
  64705. * Set the motor values.
  64706. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64707. * @param {number} force the force to apply
  64708. * @param {number} maxForce max force for this motor.
  64709. */
  64710. HingeJoint.prototype.setMotor = function (force, maxForce) {
  64711. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64712. };
  64713. /**
  64714. * Set the motor's limits.
  64715. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64716. */
  64717. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64718. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64719. };
  64720. return HingeJoint;
  64721. }(MotorEnabledJoint));
  64722. BABYLON.HingeJoint = HingeJoint;
  64723. /**
  64724. * This class represents a dual hinge physics joint (same as wheel joint)
  64725. */
  64726. var Hinge2Joint = /** @class */ (function (_super) {
  64727. __extends(Hinge2Joint, _super);
  64728. function Hinge2Joint(jointData) {
  64729. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  64730. }
  64731. /**
  64732. * Set the motor values.
  64733. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64734. * @param {number} force the force to apply
  64735. * @param {number} maxForce max force for this motor.
  64736. * @param {motorIndex} the motor's index, 0 or 1.
  64737. */
  64738. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  64739. if (motorIndex === void 0) { motorIndex = 0; }
  64740. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  64741. };
  64742. /**
  64743. * Set the motor limits.
  64744. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64745. * @param {number} upperLimit the upper limit
  64746. * @param {number} lowerLimit lower limit
  64747. * @param {motorIndex} the motor's index, 0 or 1.
  64748. */
  64749. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  64750. if (motorIndex === void 0) { motorIndex = 0; }
  64751. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  64752. };
  64753. return Hinge2Joint;
  64754. }(MotorEnabledJoint));
  64755. BABYLON.Hinge2Joint = Hinge2Joint;
  64756. })(BABYLON || (BABYLON = {}));
  64757. //# sourceMappingURL=babylon.physicsJoint.js.map
  64758. var BABYLON;
  64759. (function (BABYLON) {
  64760. var PhysicsImpostor = /** @class */ (function () {
  64761. function PhysicsImpostor(object, type, _options, _scene) {
  64762. if (_options === void 0) { _options = { mass: 0 }; }
  64763. var _this = this;
  64764. this.object = object;
  64765. this.type = type;
  64766. this._options = _options;
  64767. this._scene = _scene;
  64768. this._bodyUpdateRequired = false;
  64769. this._onBeforePhysicsStepCallbacks = new Array();
  64770. this._onAfterPhysicsStepCallbacks = new Array();
  64771. this._onPhysicsCollideCallbacks = [];
  64772. this._deltaPosition = BABYLON.Vector3.Zero();
  64773. this._isDisposed = false;
  64774. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  64775. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  64776. /**
  64777. * this function is executed by the physics engine.
  64778. */
  64779. this.beforeStep = function () {
  64780. if (!_this._physicsEngine) {
  64781. return;
  64782. }
  64783. if (_this._options.ignoreParent && _this.object.parent) {
  64784. _this._tmpPositionWithDelta.copyFrom(_this.object.getAbsolutePosition());
  64785. //this.object.getAbsolutePosition().subtractToRef(this._deltaPosition, this._tmpPositionWithDelta);
  64786. }
  64787. else {
  64788. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  64789. }
  64790. //conjugate deltaRotation
  64791. if (_this.object.rotationQuaternion) {
  64792. if (_this._deltaRotationConjugated) {
  64793. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  64794. }
  64795. else {
  64796. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  64797. }
  64798. }
  64799. // Only if not disabled
  64800. if (!_this._options.disableBidirectionalTransformation) {
  64801. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  64802. }
  64803. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  64804. func(_this);
  64805. });
  64806. };
  64807. /**
  64808. * this function is executed by the physics engine.
  64809. */
  64810. this.afterStep = function () {
  64811. if (!_this._physicsEngine) {
  64812. return;
  64813. }
  64814. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  64815. func(_this);
  64816. });
  64817. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  64818. if (_this._options.ignoreParent && _this.object.parent) {
  64819. _this.object.position.subtractInPlace(_this.object.parent.getAbsolutePosition());
  64820. }
  64821. else {
  64822. _this.object.position.addInPlace(_this._deltaPosition);
  64823. }
  64824. if (_this._deltaRotation && _this.object.rotationQuaternion) {
  64825. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  64826. }
  64827. };
  64828. /**
  64829. * Legacy collision detection event support
  64830. */
  64831. this.onCollideEvent = null;
  64832. //event and body object due to cannon's event-based architecture.
  64833. this.onCollide = function (e) {
  64834. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  64835. return;
  64836. }
  64837. if (!_this._physicsEngine) {
  64838. return;
  64839. }
  64840. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  64841. if (otherImpostor) {
  64842. // Legacy collision detection event support
  64843. if (_this.onCollideEvent) {
  64844. _this.onCollideEvent(_this, otherImpostor);
  64845. }
  64846. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  64847. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  64848. }).forEach(function (obj) {
  64849. obj.callback(_this, otherImpostor);
  64850. });
  64851. }
  64852. };
  64853. //sanity check!
  64854. if (!this.object) {
  64855. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  64856. return;
  64857. }
  64858. //legacy support for old syntax.
  64859. if (!this._scene && object.getScene) {
  64860. this._scene = object.getScene();
  64861. }
  64862. if (!this._scene) {
  64863. return;
  64864. }
  64865. this._physicsEngine = this._scene.getPhysicsEngine();
  64866. if (!this._physicsEngine) {
  64867. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  64868. }
  64869. else {
  64870. //set the object's quaternion, if not set
  64871. if (!this.object.rotationQuaternion) {
  64872. if (this.object.rotation) {
  64873. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  64874. }
  64875. else {
  64876. this.object.rotationQuaternion = new BABYLON.Quaternion();
  64877. }
  64878. }
  64879. //default options params
  64880. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  64881. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  64882. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  64883. this._joints = [];
  64884. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  64885. if (!this.object.parent || this._options.ignoreParent) {
  64886. this._init();
  64887. }
  64888. else if (this.object.parent.physicsImpostor) {
  64889. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  64890. }
  64891. }
  64892. }
  64893. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  64894. get: function () {
  64895. return this._isDisposed;
  64896. },
  64897. enumerable: true,
  64898. configurable: true
  64899. });
  64900. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  64901. get: function () {
  64902. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  64903. },
  64904. set: function (value) {
  64905. this.setMass(value);
  64906. },
  64907. enumerable: true,
  64908. configurable: true
  64909. });
  64910. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  64911. get: function () {
  64912. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  64913. },
  64914. set: function (value) {
  64915. if (!this._physicsEngine) {
  64916. return;
  64917. }
  64918. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  64919. },
  64920. enumerable: true,
  64921. configurable: true
  64922. });
  64923. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  64924. get: function () {
  64925. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  64926. },
  64927. set: function (value) {
  64928. if (!this._physicsEngine) {
  64929. return;
  64930. }
  64931. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  64932. },
  64933. enumerable: true,
  64934. configurable: true
  64935. });
  64936. /**
  64937. * This function will completly initialize this impostor.
  64938. * It will create a new body - but only if this mesh has no parent.
  64939. * If it has, this impostor will not be used other than to define the impostor
  64940. * of the child mesh.
  64941. */
  64942. PhysicsImpostor.prototype._init = function () {
  64943. if (!this._physicsEngine) {
  64944. return;
  64945. }
  64946. this._physicsEngine.removeImpostor(this);
  64947. this.physicsBody = null;
  64948. this._parent = this._parent || this._getPhysicsParent();
  64949. if (!this.parent || this._options.ignoreParent) {
  64950. this._physicsEngine.addImpostor(this);
  64951. }
  64952. };
  64953. PhysicsImpostor.prototype._getPhysicsParent = function () {
  64954. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  64955. var parentMesh = this.object.parent;
  64956. return parentMesh.physicsImpostor;
  64957. }
  64958. return null;
  64959. };
  64960. /**
  64961. * Should a new body be generated.
  64962. */
  64963. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  64964. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  64965. };
  64966. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  64967. this.forceUpdate();
  64968. };
  64969. /**
  64970. * Force a regeneration of this or the parent's impostor's body.
  64971. * Use under cautious - This will remove all joints already implemented.
  64972. */
  64973. PhysicsImpostor.prototype.forceUpdate = function () {
  64974. this._init();
  64975. if (this.parent && !this._options.ignoreParent) {
  64976. this.parent.forceUpdate();
  64977. }
  64978. };
  64979. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  64980. /*public get mesh(): AbstractMesh {
  64981. return this._mesh;
  64982. }*/
  64983. /**
  64984. * Gets the body that holds this impostor. Either its own, or its parent.
  64985. */
  64986. get: function () {
  64987. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  64988. },
  64989. /**
  64990. * Set the physics body. Used mainly by the physics engine/plugin
  64991. */
  64992. set: function (physicsBody) {
  64993. if (this._physicsBody && this._physicsEngine) {
  64994. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  64995. }
  64996. this._physicsBody = physicsBody;
  64997. this.resetUpdateFlags();
  64998. },
  64999. enumerable: true,
  65000. configurable: true
  65001. });
  65002. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65003. get: function () {
  65004. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65005. },
  65006. set: function (value) {
  65007. this._parent = value;
  65008. },
  65009. enumerable: true,
  65010. configurable: true
  65011. });
  65012. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65013. this._bodyUpdateRequired = false;
  65014. };
  65015. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65016. if (this.object.getBoundingInfo) {
  65017. var q = this.object.rotationQuaternion;
  65018. //reset rotation
  65019. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65020. //calculate the world matrix with no rotation
  65021. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65022. var boundingInfo = this.object.getBoundingInfo();
  65023. var size = void 0;
  65024. if (boundingInfo) {
  65025. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65026. }
  65027. else {
  65028. size = BABYLON.Vector3.Zero();
  65029. }
  65030. //bring back the rotation
  65031. this.object.rotationQuaternion = q;
  65032. //calculate the world matrix with the new rotation
  65033. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65034. return size;
  65035. }
  65036. else {
  65037. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65038. }
  65039. };
  65040. PhysicsImpostor.prototype.getObjectCenter = function () {
  65041. if (this.object.getBoundingInfo) {
  65042. var boundingInfo = this.object.getBoundingInfo();
  65043. if (!boundingInfo) {
  65044. return this.object.position;
  65045. }
  65046. return boundingInfo.boundingBox.centerWorld;
  65047. }
  65048. else {
  65049. return this.object.position;
  65050. }
  65051. };
  65052. /**
  65053. * Get a specific parametes from the options parameter.
  65054. */
  65055. PhysicsImpostor.prototype.getParam = function (paramName) {
  65056. return this._options[paramName];
  65057. };
  65058. /**
  65059. * Sets a specific parameter in the options given to the physics plugin
  65060. */
  65061. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65062. this._options[paramName] = value;
  65063. this._bodyUpdateRequired = true;
  65064. };
  65065. /**
  65066. * Specifically change the body's mass option. Won't recreate the physics body object
  65067. */
  65068. PhysicsImpostor.prototype.setMass = function (mass) {
  65069. if (this.getParam("mass") !== mass) {
  65070. this.setParam("mass", mass);
  65071. }
  65072. if (this._physicsEngine) {
  65073. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65074. }
  65075. };
  65076. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65077. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65078. };
  65079. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65080. if (this._physicsEngine) {
  65081. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65082. }
  65083. };
  65084. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65085. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65086. };
  65087. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65088. if (this._physicsEngine) {
  65089. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65090. }
  65091. };
  65092. /**
  65093. * Execute a function with the physics plugin native code.
  65094. * Provide a function the will have two variables - the world object and the physics body object.
  65095. */
  65096. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65097. if (this._physicsEngine) {
  65098. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65099. }
  65100. };
  65101. /**
  65102. * Register a function that will be executed before the physics world is stepping forward.
  65103. */
  65104. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65105. this._onBeforePhysicsStepCallbacks.push(func);
  65106. };
  65107. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65108. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65109. if (index > -1) {
  65110. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65111. }
  65112. else {
  65113. BABYLON.Tools.Warn("Function to remove was not found");
  65114. }
  65115. };
  65116. /**
  65117. * Register a function that will be executed after the physics step
  65118. */
  65119. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65120. this._onAfterPhysicsStepCallbacks.push(func);
  65121. };
  65122. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65123. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65124. if (index > -1) {
  65125. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65126. }
  65127. else {
  65128. BABYLON.Tools.Warn("Function to remove was not found");
  65129. }
  65130. };
  65131. /**
  65132. * register a function that will be executed when this impostor collides against a different body.
  65133. */
  65134. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65135. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65136. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65137. };
  65138. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65139. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65140. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65141. if (index > -1) {
  65142. this._onPhysicsCollideCallbacks.splice(index, 1);
  65143. }
  65144. else {
  65145. BABYLON.Tools.Warn("Function to remove was not found");
  65146. }
  65147. };
  65148. /**
  65149. * Apply a force
  65150. */
  65151. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65152. if (this._physicsEngine) {
  65153. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65154. }
  65155. return this;
  65156. };
  65157. /**
  65158. * Apply an impulse
  65159. */
  65160. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65161. if (this._physicsEngine) {
  65162. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65163. }
  65164. return this;
  65165. };
  65166. /**
  65167. * A help function to create a joint.
  65168. */
  65169. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65170. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65171. this.addJoint(otherImpostor, joint);
  65172. return this;
  65173. };
  65174. /**
  65175. * Add a joint to this impostor with a different impostor.
  65176. */
  65177. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65178. this._joints.push({
  65179. otherImpostor: otherImpostor,
  65180. joint: joint
  65181. });
  65182. if (this._physicsEngine) {
  65183. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65184. }
  65185. return this;
  65186. };
  65187. /**
  65188. * Will keep this body still, in a sleep mode.
  65189. */
  65190. PhysicsImpostor.prototype.sleep = function () {
  65191. if (this._physicsEngine) {
  65192. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65193. }
  65194. return this;
  65195. };
  65196. /**
  65197. * Wake the body up.
  65198. */
  65199. PhysicsImpostor.prototype.wakeUp = function () {
  65200. if (this._physicsEngine) {
  65201. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65202. }
  65203. return this;
  65204. };
  65205. PhysicsImpostor.prototype.clone = function (newObject) {
  65206. if (!newObject)
  65207. return null;
  65208. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65209. };
  65210. PhysicsImpostor.prototype.dispose = function () {
  65211. var _this = this;
  65212. //no dispose if no physics engine is available.
  65213. if (!this._physicsEngine) {
  65214. return;
  65215. }
  65216. this._joints.forEach(function (j) {
  65217. if (_this._physicsEngine) {
  65218. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65219. }
  65220. });
  65221. //dispose the physics body
  65222. this._physicsEngine.removeImpostor(this);
  65223. if (this.parent) {
  65224. this.parent.forceUpdate();
  65225. }
  65226. else {
  65227. /*this._object.getChildMeshes().forEach(function(mesh) {
  65228. if (mesh.physicsImpostor) {
  65229. if (disposeChildren) {
  65230. mesh.physicsImpostor.dispose();
  65231. mesh.physicsImpostor = null;
  65232. }
  65233. }
  65234. })*/
  65235. }
  65236. this._isDisposed = true;
  65237. };
  65238. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65239. this._deltaPosition.copyFrom(position);
  65240. };
  65241. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65242. if (!this._deltaRotation) {
  65243. this._deltaRotation = new BABYLON.Quaternion();
  65244. }
  65245. this._deltaRotation.copyFrom(rotation);
  65246. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65247. };
  65248. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65249. if (this._physicsEngine) {
  65250. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65251. }
  65252. return this;
  65253. };
  65254. PhysicsImpostor.prototype.getRadius = function () {
  65255. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65256. };
  65257. /**
  65258. * Sync a bone with this impostor
  65259. * @param bone The bone to sync to the impostor.
  65260. * @param boneMesh The mesh that the bone is influencing.
  65261. * @param jointPivot The pivot of the joint / bone in local space.
  65262. * @param distToJoint Optional distance from the impostor to the joint.
  65263. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65264. */
  65265. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65266. var tempVec = PhysicsImpostor._tmpVecs[0];
  65267. var mesh = this.object;
  65268. if (mesh.rotationQuaternion) {
  65269. if (adjustRotation) {
  65270. var tempQuat = PhysicsImpostor._tmpQuat;
  65271. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65272. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65273. }
  65274. else {
  65275. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65276. }
  65277. }
  65278. tempVec.x = 0;
  65279. tempVec.y = 0;
  65280. tempVec.z = 0;
  65281. if (jointPivot) {
  65282. tempVec.x = jointPivot.x;
  65283. tempVec.y = jointPivot.y;
  65284. tempVec.z = jointPivot.z;
  65285. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65286. if (distToJoint === undefined || distToJoint === null) {
  65287. distToJoint = jointPivot.length();
  65288. }
  65289. tempVec.x *= distToJoint;
  65290. tempVec.y *= distToJoint;
  65291. tempVec.z *= distToJoint;
  65292. }
  65293. if (bone.getParent()) {
  65294. tempVec.addInPlace(mesh.getAbsolutePosition());
  65295. bone.setAbsolutePosition(tempVec, boneMesh);
  65296. }
  65297. else {
  65298. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65299. boneMesh.position.x -= tempVec.x;
  65300. boneMesh.position.y -= tempVec.y;
  65301. boneMesh.position.z -= tempVec.z;
  65302. }
  65303. };
  65304. /**
  65305. * Sync impostor to a bone
  65306. * @param bone The bone that the impostor will be synced to.
  65307. * @param boneMesh The mesh that the bone is influencing.
  65308. * @param jointPivot The pivot of the joint / bone in local space.
  65309. * @param distToJoint Optional distance from the impostor to the joint.
  65310. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65311. * @param boneAxis Optional vector3 axis the bone is aligned with
  65312. */
  65313. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65314. var mesh = this.object;
  65315. if (mesh.rotationQuaternion) {
  65316. if (adjustRotation) {
  65317. var tempQuat = PhysicsImpostor._tmpQuat;
  65318. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65319. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65320. }
  65321. else {
  65322. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65323. }
  65324. }
  65325. var pos = PhysicsImpostor._tmpVecs[0];
  65326. var boneDir = PhysicsImpostor._tmpVecs[1];
  65327. if (!boneAxis) {
  65328. boneAxis = PhysicsImpostor._tmpVecs[2];
  65329. boneAxis.x = 0;
  65330. boneAxis.y = 1;
  65331. boneAxis.z = 0;
  65332. }
  65333. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65334. bone.getAbsolutePositionToRef(boneMesh, pos);
  65335. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65336. distToJoint = jointPivot.length();
  65337. }
  65338. if (distToJoint !== undefined && distToJoint !== null) {
  65339. pos.x += boneDir.x * distToJoint;
  65340. pos.y += boneDir.y * distToJoint;
  65341. pos.z += boneDir.z * distToJoint;
  65342. }
  65343. mesh.setAbsolutePosition(pos);
  65344. };
  65345. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65346. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65347. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65348. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65349. //Impostor types
  65350. PhysicsImpostor.NoImpostor = 0;
  65351. PhysicsImpostor.SphereImpostor = 1;
  65352. PhysicsImpostor.BoxImpostor = 2;
  65353. PhysicsImpostor.PlaneImpostor = 3;
  65354. PhysicsImpostor.MeshImpostor = 4;
  65355. PhysicsImpostor.CylinderImpostor = 7;
  65356. PhysicsImpostor.ParticleImpostor = 8;
  65357. PhysicsImpostor.HeightmapImpostor = 9;
  65358. return PhysicsImpostor;
  65359. }());
  65360. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65361. })(BABYLON || (BABYLON = {}));
  65362. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65363. var BABYLON;
  65364. (function (BABYLON) {
  65365. var PhysicsEngine = /** @class */ (function () {
  65366. function PhysicsEngine(gravity, _physicsPlugin) {
  65367. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65368. this._physicsPlugin = _physicsPlugin;
  65369. //new methods and parameters
  65370. this._impostors = [];
  65371. this._joints = [];
  65372. if (!this._physicsPlugin.isSupported()) {
  65373. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65374. + "Please make sure it is included.");
  65375. }
  65376. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65377. this.setGravity(gravity);
  65378. this.setTimeStep();
  65379. }
  65380. PhysicsEngine.prototype.setGravity = function (gravity) {
  65381. this.gravity = gravity;
  65382. this._physicsPlugin.setGravity(this.gravity);
  65383. };
  65384. /**
  65385. * Set the time step of the physics engine.
  65386. * default is 1/60.
  65387. * To slow it down, enter 1/600 for example.
  65388. * To speed it up, 1/30
  65389. * @param {number} newTimeStep the new timestep to apply to this world.
  65390. */
  65391. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65392. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65393. this._physicsPlugin.setTimeStep(newTimeStep);
  65394. };
  65395. /**
  65396. * Get the time step of the physics engine.
  65397. */
  65398. PhysicsEngine.prototype.getTimeStep = function () {
  65399. return this._physicsPlugin.getTimeStep();
  65400. };
  65401. PhysicsEngine.prototype.dispose = function () {
  65402. this._impostors.forEach(function (impostor) {
  65403. impostor.dispose();
  65404. });
  65405. this._physicsPlugin.dispose();
  65406. };
  65407. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65408. return this._physicsPlugin.name;
  65409. };
  65410. /**
  65411. * Adding a new impostor for the impostor tracking.
  65412. * This will be done by the impostor itself.
  65413. * @param {PhysicsImpostor} impostor the impostor to add
  65414. */
  65415. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65416. impostor.uniqueId = this._impostors.push(impostor);
  65417. //if no parent, generate the body
  65418. if (!impostor.parent) {
  65419. this._physicsPlugin.generatePhysicsBody(impostor);
  65420. }
  65421. };
  65422. /**
  65423. * Remove an impostor from the engine.
  65424. * This impostor and its mesh will not longer be updated by the physics engine.
  65425. * @param {PhysicsImpostor} impostor the impostor to remove
  65426. */
  65427. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65428. var index = this._impostors.indexOf(impostor);
  65429. if (index > -1) {
  65430. var removed = this._impostors.splice(index, 1);
  65431. //Is it needed?
  65432. if (removed.length) {
  65433. //this will also remove it from the world.
  65434. removed[0].physicsBody = null;
  65435. }
  65436. }
  65437. };
  65438. /**
  65439. * Add a joint to the physics engine
  65440. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65441. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65442. * @param {PhysicsJoint} the joint that will connect both impostors.
  65443. */
  65444. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65445. var impostorJoint = {
  65446. mainImpostor: mainImpostor,
  65447. connectedImpostor: connectedImpostor,
  65448. joint: joint
  65449. };
  65450. joint.physicsPlugin = this._physicsPlugin;
  65451. this._joints.push(impostorJoint);
  65452. this._physicsPlugin.generateJoint(impostorJoint);
  65453. };
  65454. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65455. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65456. return (impostorJoint.connectedImpostor === connectedImpostor
  65457. && impostorJoint.joint === joint
  65458. && impostorJoint.mainImpostor === mainImpostor);
  65459. });
  65460. if (matchingJoints.length) {
  65461. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65462. //TODO remove it from the list as well
  65463. }
  65464. };
  65465. /**
  65466. * Called by the scene. no need to call it.
  65467. */
  65468. PhysicsEngine.prototype._step = function (delta) {
  65469. var _this = this;
  65470. //check if any mesh has no body / requires an update
  65471. this._impostors.forEach(function (impostor) {
  65472. if (impostor.isBodyInitRequired()) {
  65473. _this._physicsPlugin.generatePhysicsBody(impostor);
  65474. }
  65475. });
  65476. if (delta > 0.1) {
  65477. delta = 0.1;
  65478. }
  65479. else if (delta <= 0) {
  65480. delta = 1.0 / 60.0;
  65481. }
  65482. this._physicsPlugin.executeStep(delta, this._impostors);
  65483. };
  65484. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65485. return this._physicsPlugin;
  65486. };
  65487. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65488. for (var i = 0; i < this._impostors.length; ++i) {
  65489. if (this._impostors[i].object === object) {
  65490. return this._impostors[i];
  65491. }
  65492. }
  65493. return null;
  65494. };
  65495. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65496. for (var i = 0; i < this._impostors.length; ++i) {
  65497. if (this._impostors[i].physicsBody === body) {
  65498. return this._impostors[i];
  65499. }
  65500. }
  65501. return null;
  65502. };
  65503. // Statics
  65504. PhysicsEngine.Epsilon = 0.001;
  65505. return PhysicsEngine;
  65506. }());
  65507. BABYLON.PhysicsEngine = PhysicsEngine;
  65508. })(BABYLON || (BABYLON = {}));
  65509. //# sourceMappingURL=babylon.physicsEngine.js.map
  65510. var BABYLON;
  65511. (function (BABYLON) {
  65512. var CannonJSPlugin = /** @class */ (function () {
  65513. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  65514. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  65515. if (iterations === void 0) { iterations = 10; }
  65516. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  65517. this.name = "CannonJSPlugin";
  65518. this._physicsMaterials = new Array();
  65519. this._fixedTimeStep = 1 / 60;
  65520. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  65521. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  65522. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  65523. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  65524. this._tmpPosition = BABYLON.Vector3.Zero();
  65525. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  65526. this._tmpUnityRotation = new BABYLON.Quaternion();
  65527. if (!this.isSupported()) {
  65528. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  65529. return;
  65530. }
  65531. this.world = new this.BJSCANNON.World();
  65532. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  65533. this.world.solver.iterations = iterations;
  65534. }
  65535. CannonJSPlugin.prototype.setGravity = function (gravity) {
  65536. this.world.gravity.copy(gravity);
  65537. };
  65538. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  65539. this._fixedTimeStep = timeStep;
  65540. };
  65541. CannonJSPlugin.prototype.getTimeStep = function () {
  65542. return this._fixedTimeStep;
  65543. };
  65544. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  65545. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  65546. };
  65547. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65548. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65549. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65550. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  65551. };
  65552. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65553. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65554. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65555. impostor.physicsBody.applyForce(impulse, worldPoint);
  65556. };
  65557. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  65558. //parent-child relationship. Does this impostor has a parent impostor?
  65559. if (impostor.parent) {
  65560. if (impostor.physicsBody) {
  65561. this.removePhysicsBody(impostor);
  65562. //TODO is that needed?
  65563. impostor.forceUpdate();
  65564. }
  65565. return;
  65566. }
  65567. //should a new body be created for this impostor?
  65568. if (impostor.isBodyInitRequired()) {
  65569. var shape = this._createShape(impostor);
  65570. //unregister events, if body is being changed
  65571. var oldBody = impostor.physicsBody;
  65572. if (oldBody) {
  65573. this.removePhysicsBody(impostor);
  65574. }
  65575. //create the body and material
  65576. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  65577. var bodyCreationObject = {
  65578. mass: impostor.getParam("mass"),
  65579. material: material
  65580. };
  65581. // A simple extend, in case native options were used.
  65582. var nativeOptions = impostor.getParam("nativeOptions");
  65583. for (var key in nativeOptions) {
  65584. if (nativeOptions.hasOwnProperty(key)) {
  65585. bodyCreationObject[key] = nativeOptions[key];
  65586. }
  65587. }
  65588. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  65589. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  65590. this.world.addEventListener("preStep", impostor.beforeStep);
  65591. this.world.addEventListener("postStep", impostor.afterStep);
  65592. impostor.physicsBody.addShape(shape);
  65593. this.world.add(impostor.physicsBody);
  65594. //try to keep the body moving in the right direction by taking old properties.
  65595. //Should be tested!
  65596. if (oldBody) {
  65597. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  65598. impostor.physicsBody[param].copy(oldBody[param]);
  65599. });
  65600. }
  65601. this._processChildMeshes(impostor);
  65602. }
  65603. //now update the body's transformation
  65604. this._updatePhysicsBodyTransformation(impostor);
  65605. };
  65606. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  65607. var _this = this;
  65608. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  65609. var currentRotation = mainImpostor.object.rotationQuaternion;
  65610. if (meshChildren.length) {
  65611. var processMesh = function (localPosition, mesh) {
  65612. if (!currentRotation || !mesh.rotationQuaternion) {
  65613. return;
  65614. }
  65615. var childImpostor = mesh.getPhysicsImpostor();
  65616. if (childImpostor) {
  65617. var parent = childImpostor.parent;
  65618. if (parent !== mainImpostor) {
  65619. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  65620. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  65621. if (childImpostor.physicsBody) {
  65622. _this.removePhysicsBody(childImpostor);
  65623. childImpostor.physicsBody = null;
  65624. }
  65625. childImpostor.parent = mainImpostor;
  65626. childImpostor.resetUpdateFlags();
  65627. 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));
  65628. //Add the mass of the children.
  65629. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  65630. }
  65631. }
  65632. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  65633. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  65634. };
  65635. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  65636. }
  65637. };
  65638. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  65639. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  65640. this.world.removeEventListener("preStep", impostor.beforeStep);
  65641. this.world.removeEventListener("postStep", impostor.afterStep);
  65642. this.world.remove(impostor.physicsBody);
  65643. };
  65644. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  65645. var mainBody = impostorJoint.mainImpostor.physicsBody;
  65646. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  65647. if (!mainBody || !connectedBody) {
  65648. return;
  65649. }
  65650. var constraint;
  65651. var jointData = impostorJoint.joint.jointData;
  65652. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  65653. var constraintData = {
  65654. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  65655. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  65656. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  65657. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  65658. maxForce: jointData.nativeParams.maxForce,
  65659. collideConnected: !!jointData.collision
  65660. };
  65661. switch (impostorJoint.joint.type) {
  65662. case BABYLON.PhysicsJoint.HingeJoint:
  65663. case BABYLON.PhysicsJoint.Hinge2Joint:
  65664. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  65665. break;
  65666. case BABYLON.PhysicsJoint.DistanceJoint:
  65667. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  65668. break;
  65669. case BABYLON.PhysicsJoint.SpringJoint:
  65670. var springData = jointData;
  65671. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  65672. restLength: springData.length,
  65673. stiffness: springData.stiffness,
  65674. damping: springData.damping,
  65675. localAnchorA: constraintData.pivotA,
  65676. localAnchorB: constraintData.pivotB
  65677. });
  65678. break;
  65679. case BABYLON.PhysicsJoint.LockJoint:
  65680. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  65681. break;
  65682. case BABYLON.PhysicsJoint.PointToPointJoint:
  65683. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  65684. default:
  65685. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  65686. break;
  65687. }
  65688. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  65689. constraint.collideConnected = !!jointData.collision;
  65690. impostorJoint.joint.physicsJoint = constraint;
  65691. //don't add spring as constraint, as it is not one.
  65692. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  65693. this.world.addConstraint(constraint);
  65694. }
  65695. else {
  65696. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  65697. constraint.applyForce();
  65698. });
  65699. }
  65700. };
  65701. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  65702. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  65703. };
  65704. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  65705. var index;
  65706. var mat;
  65707. for (index = 0; index < this._physicsMaterials.length; index++) {
  65708. mat = this._physicsMaterials[index];
  65709. if (mat.friction === friction && mat.restitution === restitution) {
  65710. return mat;
  65711. }
  65712. }
  65713. var currentMat = new this.BJSCANNON.Material(name);
  65714. currentMat.friction = friction;
  65715. currentMat.restitution = restitution;
  65716. this._physicsMaterials.push(currentMat);
  65717. return currentMat;
  65718. };
  65719. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  65720. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  65721. };
  65722. CannonJSPlugin.prototype._createShape = function (impostor) {
  65723. var object = impostor.object;
  65724. var returnValue;
  65725. var extendSize = impostor.getObjectExtendSize();
  65726. switch (impostor.type) {
  65727. case BABYLON.PhysicsImpostor.SphereImpostor:
  65728. var radiusX = extendSize.x;
  65729. var radiusY = extendSize.y;
  65730. var radiusZ = extendSize.z;
  65731. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  65732. break;
  65733. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  65734. case BABYLON.PhysicsImpostor.CylinderImpostor:
  65735. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  65736. break;
  65737. case BABYLON.PhysicsImpostor.BoxImpostor:
  65738. var box = extendSize.scale(0.5);
  65739. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  65740. break;
  65741. case BABYLON.PhysicsImpostor.PlaneImpostor:
  65742. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  65743. returnValue = new this.BJSCANNON.Plane();
  65744. break;
  65745. case BABYLON.PhysicsImpostor.MeshImpostor:
  65746. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  65747. var rawFaces = object.getIndices ? object.getIndices() : [];
  65748. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  65749. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  65750. break;
  65751. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  65752. returnValue = this._createHeightmap(object);
  65753. break;
  65754. case BABYLON.PhysicsImpostor.ParticleImpostor:
  65755. returnValue = new this.BJSCANNON.Particle();
  65756. break;
  65757. }
  65758. return returnValue;
  65759. };
  65760. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  65761. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  65762. var matrix = new Array();
  65763. //For now pointDepth will not be used and will be automatically calculated.
  65764. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  65765. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  65766. var boundingInfo = (object.getBoundingInfo());
  65767. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.z);
  65768. var minY = boundingInfo.boundingBox.extendSizeWorld.y;
  65769. var elementSize = dim * 2 / arraySize;
  65770. for (var i = 0; i < pos.length; i = i + 3) {
  65771. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  65772. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  65773. var y = pos[i + 1] + minY;
  65774. if (!matrix[x]) {
  65775. matrix[x] = [];
  65776. }
  65777. if (!matrix[x][z]) {
  65778. matrix[x][z] = y;
  65779. }
  65780. matrix[x][z] = Math.max(y, matrix[x][z]);
  65781. }
  65782. for (var x = 0; x <= arraySize; ++x) {
  65783. if (!matrix[x]) {
  65784. var loc = 1;
  65785. while (!matrix[(x + loc) % arraySize]) {
  65786. loc++;
  65787. }
  65788. matrix[x] = matrix[(x + loc) % arraySize].slice();
  65789. //console.log("missing x", x);
  65790. }
  65791. for (var z = 0; z <= arraySize; ++z) {
  65792. if (!matrix[x][z]) {
  65793. var loc = 1;
  65794. var newValue;
  65795. while (newValue === undefined) {
  65796. newValue = matrix[x][(z + loc++) % arraySize];
  65797. }
  65798. matrix[x][z] = newValue;
  65799. }
  65800. }
  65801. }
  65802. var shape = new this.BJSCANNON.Heightfield(matrix, {
  65803. elementSize: elementSize
  65804. });
  65805. //For future reference, needed for body transformation
  65806. shape.minY = minY;
  65807. return shape;
  65808. };
  65809. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  65810. var object = impostor.object;
  65811. //make sure it is updated...
  65812. object.computeWorldMatrix && object.computeWorldMatrix(true);
  65813. // The delta between the mesh position and the mesh bounding box center
  65814. var center = impostor.getObjectCenter();
  65815. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  65816. this._tmpPosition.copyFrom(center);
  65817. var quaternion = object.rotationQuaternion;
  65818. if (!quaternion) {
  65819. return;
  65820. }
  65821. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  65822. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  65823. //-90 DEG in X, precalculated
  65824. quaternion = quaternion.multiply(this._minus90X);
  65825. //Invert! (Precalculated, 90 deg in X)
  65826. //No need to clone. this will never change.
  65827. impostor.setDeltaRotation(this._plus90X);
  65828. }
  65829. //If it is a heightfield, if should be centered.
  65830. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  65831. var mesh = object;
  65832. var boundingInfo = mesh.getBoundingInfo();
  65833. //calculate the correct body position:
  65834. var rotationQuaternion = mesh.rotationQuaternion;
  65835. mesh.rotationQuaternion = this._tmpUnityRotation;
  65836. mesh.computeWorldMatrix(true);
  65837. //get original center with no rotation
  65838. var c = center.clone();
  65839. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  65840. //rotation is back
  65841. mesh.rotationQuaternion = rotationQuaternion;
  65842. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  65843. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  65844. mesh.setPivotMatrix(p);
  65845. mesh.computeWorldMatrix(true);
  65846. //calculate the translation
  65847. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  65848. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  65849. //add it inverted to the delta
  65850. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  65851. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  65852. mesh.setPivotMatrix(oldPivot);
  65853. mesh.computeWorldMatrix(true);
  65854. }
  65855. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  65856. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  65857. this._tmpPosition.copyFrom(object.position);
  65858. }
  65859. impostor.setDeltaPosition(this._tmpDeltaPosition);
  65860. //Now update the impostor object
  65861. impostor.physicsBody.position.copy(this._tmpPosition);
  65862. impostor.physicsBody.quaternion.copy(quaternion);
  65863. };
  65864. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  65865. impostor.object.position.copyFrom(impostor.physicsBody.position);
  65866. if (impostor.object.rotationQuaternion) {
  65867. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  65868. }
  65869. };
  65870. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  65871. impostor.physicsBody.position.copy(newPosition);
  65872. impostor.physicsBody.quaternion.copy(newRotation);
  65873. };
  65874. CannonJSPlugin.prototype.isSupported = function () {
  65875. return this.BJSCANNON !== undefined;
  65876. };
  65877. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  65878. impostor.physicsBody.velocity.copy(velocity);
  65879. };
  65880. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  65881. impostor.physicsBody.angularVelocity.copy(velocity);
  65882. };
  65883. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  65884. var v = impostor.physicsBody.velocity;
  65885. if (!v) {
  65886. return null;
  65887. }
  65888. return new BABYLON.Vector3(v.x, v.y, v.z);
  65889. };
  65890. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  65891. var v = impostor.physicsBody.angularVelocity;
  65892. if (!v) {
  65893. return null;
  65894. }
  65895. return new BABYLON.Vector3(v.x, v.y, v.z);
  65896. };
  65897. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  65898. impostor.physicsBody.mass = mass;
  65899. impostor.physicsBody.updateMassProperties();
  65900. };
  65901. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  65902. return impostor.physicsBody.mass;
  65903. };
  65904. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  65905. return impostor.physicsBody.material.friction;
  65906. };
  65907. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  65908. impostor.physicsBody.material.friction = friction;
  65909. };
  65910. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  65911. return impostor.physicsBody.material.restitution;
  65912. };
  65913. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  65914. impostor.physicsBody.material.restitution = restitution;
  65915. };
  65916. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  65917. impostor.physicsBody.sleep();
  65918. };
  65919. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  65920. impostor.physicsBody.wakeUp();
  65921. };
  65922. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  65923. joint.physicsJoint.distance = maxDistance;
  65924. };
  65925. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  65926. // if (!motorIndex) {
  65927. // joint.physicsJoint.enableMotor();
  65928. // }
  65929. // }
  65930. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  65931. // if (!motorIndex) {
  65932. // joint.physicsJoint.disableMotor();
  65933. // }
  65934. // }
  65935. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  65936. if (!motorIndex) {
  65937. joint.physicsJoint.enableMotor();
  65938. joint.physicsJoint.setMotorSpeed(speed);
  65939. if (maxForce) {
  65940. this.setLimit(joint, maxForce);
  65941. }
  65942. }
  65943. };
  65944. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  65945. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  65946. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  65947. };
  65948. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  65949. var body = impostor.physicsBody;
  65950. mesh.position.x = body.position.x;
  65951. mesh.position.y = body.position.y;
  65952. mesh.position.z = body.position.z;
  65953. if (mesh.rotationQuaternion) {
  65954. mesh.rotationQuaternion.x = body.quaternion.x;
  65955. mesh.rotationQuaternion.y = body.quaternion.y;
  65956. mesh.rotationQuaternion.z = body.quaternion.z;
  65957. mesh.rotationQuaternion.w = body.quaternion.w;
  65958. }
  65959. };
  65960. CannonJSPlugin.prototype.getRadius = function (impostor) {
  65961. var shape = impostor.physicsBody.shapes[0];
  65962. return shape.boundingSphereRadius;
  65963. };
  65964. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  65965. var shape = impostor.physicsBody.shapes[0];
  65966. result.x = shape.halfExtents.x * 2;
  65967. result.y = shape.halfExtents.y * 2;
  65968. result.z = shape.halfExtents.z * 2;
  65969. };
  65970. CannonJSPlugin.prototype.dispose = function () {
  65971. };
  65972. return CannonJSPlugin;
  65973. }());
  65974. BABYLON.CannonJSPlugin = CannonJSPlugin;
  65975. })(BABYLON || (BABYLON = {}));
  65976. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  65977. var BABYLON;
  65978. (function (BABYLON) {
  65979. var OimoJSPlugin = /** @class */ (function () {
  65980. function OimoJSPlugin(iterations) {
  65981. this.name = "OimoJSPlugin";
  65982. this._tmpImpostorsArray = [];
  65983. this._tmpPositionVector = BABYLON.Vector3.Zero();
  65984. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  65985. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  65986. this.world.worldscale(1);
  65987. this.world.clear();
  65988. //making sure no stats are calculated
  65989. this.world.isNoStat = true;
  65990. }
  65991. OimoJSPlugin.prototype.setGravity = function (gravity) {
  65992. this.world.gravity.copy(gravity);
  65993. };
  65994. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  65995. this.world.timeStep = timeStep;
  65996. };
  65997. OimoJSPlugin.prototype.getTimeStep = function () {
  65998. return this.world.timeStep;
  65999. };
  66000. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66001. var _this = this;
  66002. impostors.forEach(function (impostor) {
  66003. impostor.beforeStep();
  66004. });
  66005. this.world.step();
  66006. impostors.forEach(function (impostor) {
  66007. impostor.afterStep();
  66008. //update the ordered impostors array
  66009. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66010. });
  66011. //check for collisions
  66012. var contact = this.world.contacts;
  66013. while (contact !== null) {
  66014. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66015. contact = contact.next;
  66016. continue;
  66017. }
  66018. //is this body colliding with any other? get the impostor
  66019. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66020. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66021. if (!mainImpostor || !collidingImpostor) {
  66022. contact = contact.next;
  66023. continue;
  66024. }
  66025. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66026. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66027. contact = contact.next;
  66028. }
  66029. };
  66030. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66031. var mass = impostor.physicsBody.massInfo.mass;
  66032. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66033. };
  66034. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66035. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66036. this.applyImpulse(impostor, force, contactPoint);
  66037. };
  66038. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66039. var _this = this;
  66040. //parent-child relationship. Does this impostor has a parent impostor?
  66041. if (impostor.parent) {
  66042. if (impostor.physicsBody) {
  66043. this.removePhysicsBody(impostor);
  66044. //TODO is that needed?
  66045. impostor.forceUpdate();
  66046. }
  66047. return;
  66048. }
  66049. if (impostor.isBodyInitRequired()) {
  66050. var bodyConfig = {
  66051. name: impostor.uniqueId,
  66052. //Oimo must have mass, also for static objects.
  66053. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66054. size: [],
  66055. type: [],
  66056. pos: [],
  66057. rot: [],
  66058. move: impostor.getParam("mass") !== 0,
  66059. //Supporting older versions of Oimo
  66060. world: this.world
  66061. };
  66062. var impostors = [impostor];
  66063. var addToArray = function (parent) {
  66064. if (!parent.getChildMeshes)
  66065. return;
  66066. parent.getChildMeshes().forEach(function (m) {
  66067. if (m.physicsImpostor) {
  66068. impostors.push(m.physicsImpostor);
  66069. //m.physicsImpostor._init();
  66070. }
  66071. });
  66072. };
  66073. addToArray(impostor.object);
  66074. var checkWithEpsilon_1 = function (value) {
  66075. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66076. };
  66077. impostors.forEach(function (i) {
  66078. if (!impostor.object.rotationQuaternion) {
  66079. return;
  66080. }
  66081. //get the correct bounding box
  66082. var oldQuaternion = i.object.rotationQuaternion;
  66083. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66084. x: impostor.object.rotationQuaternion.x,
  66085. y: impostor.object.rotationQuaternion.y,
  66086. z: impostor.object.rotationQuaternion.z,
  66087. s: impostor.object.rotationQuaternion.w
  66088. });
  66089. var extendSize = i.getObjectExtendSize();
  66090. if (i === impostor) {
  66091. var center = impostor.getObjectCenter();
  66092. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66093. //Can also use Array.prototype.push.apply
  66094. bodyConfig.pos.push(center.x);
  66095. bodyConfig.pos.push(center.y);
  66096. bodyConfig.pos.push(center.z);
  66097. //tmp solution
  66098. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66099. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66100. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66101. }
  66102. else {
  66103. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66104. bodyConfig.pos.push(localPosition.x);
  66105. bodyConfig.pos.push(localPosition.y);
  66106. bodyConfig.pos.push(localPosition.z);
  66107. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66108. bodyConfig.rot.push(0);
  66109. bodyConfig.rot.push(0);
  66110. bodyConfig.rot.push(0);
  66111. }
  66112. // register mesh
  66113. switch (i.type) {
  66114. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66115. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66116. case BABYLON.PhysicsImpostor.SphereImpostor:
  66117. var radiusX = extendSize.x;
  66118. var radiusY = extendSize.y;
  66119. var radiusZ = extendSize.z;
  66120. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66121. bodyConfig.type.push('sphere');
  66122. //due to the way oimo works with compounds, add 3 times
  66123. bodyConfig.size.push(size);
  66124. bodyConfig.size.push(size);
  66125. bodyConfig.size.push(size);
  66126. break;
  66127. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66128. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66129. var sizeY = checkWithEpsilon_1(extendSize.y);
  66130. bodyConfig.type.push('cylinder');
  66131. bodyConfig.size.push(sizeX);
  66132. bodyConfig.size.push(sizeY);
  66133. //due to the way oimo works with compounds, add one more value.
  66134. bodyConfig.size.push(sizeY);
  66135. break;
  66136. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66137. case BABYLON.PhysicsImpostor.BoxImpostor:
  66138. default:
  66139. var sizeX = checkWithEpsilon_1(extendSize.x);
  66140. var sizeY = checkWithEpsilon_1(extendSize.y);
  66141. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66142. bodyConfig.type.push('box');
  66143. bodyConfig.size.push(sizeX);
  66144. bodyConfig.size.push(sizeY);
  66145. bodyConfig.size.push(sizeZ);
  66146. break;
  66147. }
  66148. //actually not needed, but hey...
  66149. i.object.rotationQuaternion = oldQuaternion;
  66150. });
  66151. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66152. }
  66153. else {
  66154. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66155. }
  66156. impostor.setDeltaPosition(this._tmpPositionVector);
  66157. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66158. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66159. };
  66160. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66161. //impostor.physicsBody.dispose();
  66162. //Same as : (older oimo versions)
  66163. this.world.removeRigidBody(impostor.physicsBody);
  66164. };
  66165. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66166. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66167. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66168. if (!mainBody || !connectedBody) {
  66169. return;
  66170. }
  66171. var jointData = impostorJoint.joint.jointData;
  66172. var options = jointData.nativeParams || {};
  66173. var type;
  66174. var nativeJointData = {
  66175. body1: mainBody,
  66176. body2: connectedBody,
  66177. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66178. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66179. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66180. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66181. min: options.min,
  66182. max: options.max,
  66183. collision: options.collision || jointData.collision,
  66184. spring: options.spring,
  66185. //supporting older version of Oimo
  66186. world: this.world
  66187. };
  66188. switch (impostorJoint.joint.type) {
  66189. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66190. type = "jointBall";
  66191. break;
  66192. case BABYLON.PhysicsJoint.SpringJoint:
  66193. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66194. var springData = jointData;
  66195. nativeJointData.min = springData.length || nativeJointData.min;
  66196. //Max should also be set, just make sure it is at least min
  66197. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66198. case BABYLON.PhysicsJoint.DistanceJoint:
  66199. type = "jointDistance";
  66200. nativeJointData.max = jointData.maxDistance;
  66201. break;
  66202. case BABYLON.PhysicsJoint.PrismaticJoint:
  66203. type = "jointPrisme";
  66204. break;
  66205. case BABYLON.PhysicsJoint.SliderJoint:
  66206. type = "jointSlide";
  66207. break;
  66208. case BABYLON.PhysicsJoint.WheelJoint:
  66209. type = "jointWheel";
  66210. break;
  66211. case BABYLON.PhysicsJoint.HingeJoint:
  66212. default:
  66213. type = "jointHinge";
  66214. break;
  66215. }
  66216. nativeJointData.type = type;
  66217. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66218. };
  66219. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66220. //Bug in Oimo prevents us from disposing a joint in the playground
  66221. //joint.joint.physicsJoint.dispose();
  66222. //So we will bruteforce it!
  66223. try {
  66224. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66225. }
  66226. catch (e) {
  66227. BABYLON.Tools.Warn(e);
  66228. }
  66229. };
  66230. OimoJSPlugin.prototype.isSupported = function () {
  66231. return this.BJSOIMO !== undefined;
  66232. };
  66233. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66234. if (!impostor.physicsBody.sleeping) {
  66235. //TODO check that
  66236. if (impostor.physicsBody.shapes.next) {
  66237. var parentShape = this._getLastShape(impostor.physicsBody);
  66238. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66239. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66240. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66241. }
  66242. else {
  66243. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66244. }
  66245. if (impostor.object.rotationQuaternion) {
  66246. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66247. impostor.object.rotationQuaternion.normalize();
  66248. }
  66249. }
  66250. };
  66251. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66252. var body = impostor.physicsBody;
  66253. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66254. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66255. body.syncShapes();
  66256. body.awake();
  66257. };
  66258. OimoJSPlugin.prototype._getLastShape = function (body) {
  66259. var lastShape = body.shapes;
  66260. while (lastShape.next) {
  66261. lastShape = lastShape.next;
  66262. }
  66263. return lastShape;
  66264. };
  66265. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66266. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66267. };
  66268. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66269. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66270. };
  66271. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66272. var v = impostor.physicsBody.linearVelocity;
  66273. if (!v) {
  66274. return null;
  66275. }
  66276. return new BABYLON.Vector3(v.x, v.y, v.z);
  66277. };
  66278. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66279. var v = impostor.physicsBody.angularVelocity;
  66280. if (!v) {
  66281. return null;
  66282. }
  66283. return new BABYLON.Vector3(v.x, v.y, v.z);
  66284. };
  66285. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66286. var staticBody = mass === 0;
  66287. //this will actually set the body's density and not its mass.
  66288. //But this is how oimo treats the mass variable.
  66289. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66290. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66291. };
  66292. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66293. return impostor.physicsBody.shapes.density;
  66294. };
  66295. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66296. return impostor.physicsBody.shapes.friction;
  66297. };
  66298. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66299. impostor.physicsBody.shapes.friction = friction;
  66300. };
  66301. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66302. return impostor.physicsBody.shapes.restitution;
  66303. };
  66304. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66305. impostor.physicsBody.shapes.restitution = restitution;
  66306. };
  66307. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66308. impostor.physicsBody.sleep();
  66309. };
  66310. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66311. impostor.physicsBody.awake();
  66312. };
  66313. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66314. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66315. if (minDistance !== void 0) {
  66316. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66317. }
  66318. };
  66319. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66320. //TODO separate rotational and transational motors.
  66321. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66322. if (motor) {
  66323. motor.setMotor(speed, maxForce);
  66324. }
  66325. };
  66326. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66327. //TODO separate rotational and transational motors.
  66328. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66329. if (motor) {
  66330. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66331. }
  66332. };
  66333. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66334. var body = impostor.physicsBody;
  66335. mesh.position.x = body.position.x;
  66336. mesh.position.y = body.position.y;
  66337. mesh.position.z = body.position.z;
  66338. if (mesh.rotationQuaternion) {
  66339. mesh.rotationQuaternion.x = body.orientation.x;
  66340. mesh.rotationQuaternion.y = body.orientation.y;
  66341. mesh.rotationQuaternion.z = body.orientation.z;
  66342. mesh.rotationQuaternion.w = body.orientation.s;
  66343. }
  66344. };
  66345. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66346. return impostor.physicsBody.shapes.radius;
  66347. };
  66348. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66349. var shape = impostor.physicsBody.shapes;
  66350. result.x = shape.halfWidth * 2;
  66351. result.y = shape.halfHeight * 2;
  66352. result.z = shape.halfDepth * 2;
  66353. };
  66354. OimoJSPlugin.prototype.dispose = function () {
  66355. this.world.clear();
  66356. };
  66357. return OimoJSPlugin;
  66358. }());
  66359. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66360. })(BABYLON || (BABYLON = {}));
  66361. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66362. var BABYLON;
  66363. (function (BABYLON) {
  66364. var Internals;
  66365. (function (Internals) {
  66366. /*
  66367. * Based on jsTGALoader - Javascript loader for TGA file
  66368. * By Vincent Thibault
  66369. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66370. */
  66371. var TGATools = /** @class */ (function () {
  66372. function TGATools() {
  66373. }
  66374. TGATools.GetTGAHeader = function (data) {
  66375. var offset = 0;
  66376. var header = {
  66377. id_length: data[offset++],
  66378. colormap_type: data[offset++],
  66379. image_type: data[offset++],
  66380. colormap_index: data[offset++] | data[offset++] << 8,
  66381. colormap_length: data[offset++] | data[offset++] << 8,
  66382. colormap_size: data[offset++],
  66383. origin: [
  66384. data[offset++] | data[offset++] << 8,
  66385. data[offset++] | data[offset++] << 8
  66386. ],
  66387. width: data[offset++] | data[offset++] << 8,
  66388. height: data[offset++] | data[offset++] << 8,
  66389. pixel_size: data[offset++],
  66390. flags: data[offset++]
  66391. };
  66392. return header;
  66393. };
  66394. TGATools.UploadContent = function (gl, data) {
  66395. // Not enough data to contain header ?
  66396. if (data.length < 19) {
  66397. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66398. return;
  66399. }
  66400. // Read Header
  66401. var offset = 18;
  66402. var header = TGATools.GetTGAHeader(data);
  66403. // Assume it's a valid Targa file.
  66404. if (header.id_length + offset > data.length) {
  66405. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66406. return;
  66407. }
  66408. // Skip not needed data
  66409. offset += header.id_length;
  66410. var use_rle = false;
  66411. var use_pal = false;
  66412. var use_rgb = false;
  66413. var use_grey = false;
  66414. // Get some informations.
  66415. switch (header.image_type) {
  66416. case TGATools._TYPE_RLE_INDEXED:
  66417. use_rle = true;
  66418. case TGATools._TYPE_INDEXED:
  66419. use_pal = true;
  66420. break;
  66421. case TGATools._TYPE_RLE_RGB:
  66422. use_rle = true;
  66423. case TGATools._TYPE_RGB:
  66424. use_rgb = true;
  66425. break;
  66426. case TGATools._TYPE_RLE_GREY:
  66427. use_rle = true;
  66428. case TGATools._TYPE_GREY:
  66429. use_grey = true;
  66430. break;
  66431. }
  66432. var pixel_data;
  66433. // var numAlphaBits = header.flags & 0xf;
  66434. var pixel_size = header.pixel_size >> 3;
  66435. var pixel_total = header.width * header.height * pixel_size;
  66436. // Read palettes
  66437. var palettes;
  66438. if (use_pal) {
  66439. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66440. }
  66441. // Read LRE
  66442. if (use_rle) {
  66443. pixel_data = new Uint8Array(pixel_total);
  66444. var c, count, i;
  66445. var localOffset = 0;
  66446. var pixels = new Uint8Array(pixel_size);
  66447. while (offset < pixel_total && localOffset < pixel_total) {
  66448. c = data[offset++];
  66449. count = (c & 0x7f) + 1;
  66450. // RLE pixels
  66451. if (c & 0x80) {
  66452. // Bind pixel tmp array
  66453. for (i = 0; i < pixel_size; ++i) {
  66454. pixels[i] = data[offset++];
  66455. }
  66456. // Copy pixel array
  66457. for (i = 0; i < count; ++i) {
  66458. pixel_data.set(pixels, localOffset + i * pixel_size);
  66459. }
  66460. localOffset += pixel_size * count;
  66461. }
  66462. else {
  66463. count *= pixel_size;
  66464. for (i = 0; i < count; ++i) {
  66465. pixel_data[localOffset + i] = data[offset++];
  66466. }
  66467. localOffset += count;
  66468. }
  66469. }
  66470. }
  66471. else {
  66472. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  66473. }
  66474. // Load to texture
  66475. var x_start, y_start, x_step, y_step, y_end, x_end;
  66476. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  66477. default:
  66478. case TGATools._ORIGIN_UL:
  66479. x_start = 0;
  66480. x_step = 1;
  66481. x_end = header.width;
  66482. y_start = 0;
  66483. y_step = 1;
  66484. y_end = header.height;
  66485. break;
  66486. case TGATools._ORIGIN_BL:
  66487. x_start = 0;
  66488. x_step = 1;
  66489. x_end = header.width;
  66490. y_start = header.height - 1;
  66491. y_step = -1;
  66492. y_end = -1;
  66493. break;
  66494. case TGATools._ORIGIN_UR:
  66495. x_start = header.width - 1;
  66496. x_step = -1;
  66497. x_end = -1;
  66498. y_start = 0;
  66499. y_step = 1;
  66500. y_end = header.height;
  66501. break;
  66502. case TGATools._ORIGIN_BR:
  66503. x_start = header.width - 1;
  66504. x_step = -1;
  66505. x_end = -1;
  66506. y_start = header.height - 1;
  66507. y_step = -1;
  66508. y_end = -1;
  66509. break;
  66510. }
  66511. // Load the specify method
  66512. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  66513. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  66514. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  66515. };
  66516. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66517. var image = pixel_data, colormap = palettes;
  66518. var width = header.width, height = header.height;
  66519. var color, i = 0, x, y;
  66520. var imageData = new Uint8Array(width * height * 4);
  66521. for (y = y_start; y !== y_end; y += y_step) {
  66522. for (x = x_start; x !== x_end; x += x_step, i++) {
  66523. color = image[i];
  66524. imageData[(x + width * y) * 4 + 3] = 255;
  66525. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  66526. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  66527. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  66528. }
  66529. }
  66530. return imageData;
  66531. };
  66532. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66533. var image = pixel_data;
  66534. var width = header.width, height = header.height;
  66535. var color, i = 0, x, y;
  66536. var imageData = new Uint8Array(width * height * 4);
  66537. for (y = y_start; y !== y_end; y += y_step) {
  66538. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66539. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  66540. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  66541. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  66542. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  66543. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  66544. }
  66545. }
  66546. return imageData;
  66547. };
  66548. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66549. var image = pixel_data;
  66550. var width = header.width, height = header.height;
  66551. var i = 0, x, y;
  66552. var imageData = new Uint8Array(width * height * 4);
  66553. for (y = y_start; y !== y_end; y += y_step) {
  66554. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  66555. imageData[(x + width * y) * 4 + 3] = 255;
  66556. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66557. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66558. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66559. }
  66560. }
  66561. return imageData;
  66562. };
  66563. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66564. var image = pixel_data;
  66565. var width = header.width, height = header.height;
  66566. var i = 0, x, y;
  66567. var imageData = new Uint8Array(width * height * 4);
  66568. for (y = y_start; y !== y_end; y += y_step) {
  66569. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  66570. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66571. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66572. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66573. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  66574. }
  66575. }
  66576. return imageData;
  66577. };
  66578. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66579. var image = pixel_data;
  66580. var width = header.width, height = header.height;
  66581. var color, i = 0, x, y;
  66582. var imageData = new Uint8Array(width * height * 4);
  66583. for (y = y_start; y !== y_end; y += y_step) {
  66584. for (x = x_start; x !== x_end; x += x_step, i++) {
  66585. color = image[i];
  66586. imageData[(x + width * y) * 4 + 0] = color;
  66587. imageData[(x + width * y) * 4 + 1] = color;
  66588. imageData[(x + width * y) * 4 + 2] = color;
  66589. imageData[(x + width * y) * 4 + 3] = 255;
  66590. }
  66591. }
  66592. return imageData;
  66593. };
  66594. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66595. var image = pixel_data;
  66596. var width = header.width, height = header.height;
  66597. var i = 0, x, y;
  66598. var imageData = new Uint8Array(width * height * 4);
  66599. for (y = y_start; y !== y_end; y += y_step) {
  66600. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66601. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  66602. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  66603. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66604. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  66605. }
  66606. }
  66607. return imageData;
  66608. };
  66609. //private static _TYPE_NO_DATA = 0;
  66610. TGATools._TYPE_INDEXED = 1;
  66611. TGATools._TYPE_RGB = 2;
  66612. TGATools._TYPE_GREY = 3;
  66613. TGATools._TYPE_RLE_INDEXED = 9;
  66614. TGATools._TYPE_RLE_RGB = 10;
  66615. TGATools._TYPE_RLE_GREY = 11;
  66616. TGATools._ORIGIN_MASK = 0x30;
  66617. TGATools._ORIGIN_SHIFT = 0x04;
  66618. TGATools._ORIGIN_BL = 0x00;
  66619. TGATools._ORIGIN_BR = 0x01;
  66620. TGATools._ORIGIN_UL = 0x02;
  66621. TGATools._ORIGIN_UR = 0x03;
  66622. return TGATools;
  66623. }());
  66624. Internals.TGATools = TGATools;
  66625. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66626. })(BABYLON || (BABYLON = {}));
  66627. //# sourceMappingURL=babylon.tga.js.map
  66628. var BABYLON;
  66629. (function (BABYLON) {
  66630. var Internals;
  66631. (function (Internals) {
  66632. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  66633. // All values and structures referenced from:
  66634. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  66635. var DDS_MAGIC = 0x20534444;
  66636. var
  66637. //DDSD_CAPS = 0x1,
  66638. //DDSD_HEIGHT = 0x2,
  66639. //DDSD_WIDTH = 0x4,
  66640. //DDSD_PITCH = 0x8,
  66641. //DDSD_PIXELFORMAT = 0x1000,
  66642. DDSD_MIPMAPCOUNT = 0x20000;
  66643. //DDSD_LINEARSIZE = 0x80000,
  66644. //DDSD_DEPTH = 0x800000;
  66645. // var DDSCAPS_COMPLEX = 0x8,
  66646. // DDSCAPS_MIPMAP = 0x400000,
  66647. // DDSCAPS_TEXTURE = 0x1000;
  66648. var DDSCAPS2_CUBEMAP = 0x200;
  66649. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  66650. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  66651. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  66652. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  66653. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  66654. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  66655. // DDSCAPS2_VOLUME = 0x200000;
  66656. var
  66657. //DDPF_ALPHAPIXELS = 0x1,
  66658. //DDPF_ALPHA = 0x2,
  66659. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  66660. //DDPF_YUV = 0x200,
  66661. DDPF_LUMINANCE = 0x20000;
  66662. function FourCCToInt32(value) {
  66663. return value.charCodeAt(0) +
  66664. (value.charCodeAt(1) << 8) +
  66665. (value.charCodeAt(2) << 16) +
  66666. (value.charCodeAt(3) << 24);
  66667. }
  66668. function Int32ToFourCC(value) {
  66669. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  66670. }
  66671. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  66672. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  66673. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  66674. var FOURCC_DX10 = FourCCToInt32("DX10");
  66675. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  66676. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  66677. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  66678. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  66679. var headerLengthInt = 31; // The header length in 32 bit ints
  66680. // Offsets into the header array
  66681. var off_magic = 0;
  66682. var off_size = 1;
  66683. var off_flags = 2;
  66684. var off_height = 3;
  66685. var off_width = 4;
  66686. var off_mipmapCount = 7;
  66687. var off_pfFlags = 20;
  66688. var off_pfFourCC = 21;
  66689. var off_RGBbpp = 22;
  66690. // var off_RMask = 23;
  66691. // var off_GMask = 24;
  66692. // var off_BMask = 25;
  66693. // var off_AMask = 26;
  66694. // var off_caps1 = 27;
  66695. var off_caps2 = 28;
  66696. // var off_caps3 = 29;
  66697. // var off_caps4 = 30;
  66698. var off_dxgiFormat = 32;
  66699. ;
  66700. var DDSTools = /** @class */ (function () {
  66701. function DDSTools() {
  66702. }
  66703. DDSTools.GetDDSInfo = function (arrayBuffer) {
  66704. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  66705. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  66706. var mipmapCount = 1;
  66707. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  66708. mipmapCount = Math.max(1, header[off_mipmapCount]);
  66709. }
  66710. var fourCC = header[off_pfFourCC];
  66711. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  66712. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66713. switch (fourCC) {
  66714. case FOURCC_D3DFMT_R16G16B16A16F:
  66715. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66716. break;
  66717. case FOURCC_D3DFMT_R32G32B32A32F:
  66718. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66719. break;
  66720. case FOURCC_DX10:
  66721. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  66722. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66723. break;
  66724. }
  66725. }
  66726. return {
  66727. width: header[off_width],
  66728. height: header[off_height],
  66729. mipmapCount: mipmapCount,
  66730. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  66731. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  66732. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  66733. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  66734. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  66735. dxgiFormat: dxgiFormat,
  66736. textureType: textureType
  66737. };
  66738. };
  66739. DDSTools._ToHalfFloat = function (value) {
  66740. if (!DDSTools._FloatView) {
  66741. DDSTools._FloatView = new Float32Array(1);
  66742. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  66743. }
  66744. DDSTools._FloatView[0] = value;
  66745. var x = DDSTools._Int32View[0];
  66746. var bits = (x >> 16) & 0x8000; /* Get the sign */
  66747. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  66748. var e = (x >> 23) & 0xff; /* Using int is faster here */
  66749. /* If zero, or denormal, or exponent underflows too much for a denormal
  66750. * half, return signed zero. */
  66751. if (e < 103) {
  66752. return bits;
  66753. }
  66754. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  66755. if (e > 142) {
  66756. bits |= 0x7c00;
  66757. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  66758. * not Inf, so make sure we set one mantissa bit too. */
  66759. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  66760. return bits;
  66761. }
  66762. /* If exponent underflows but not too much, return a denormal */
  66763. if (e < 113) {
  66764. m |= 0x0800;
  66765. /* Extra rounding may overflow and set mantissa to 0 and exponent
  66766. * to 1, which is OK. */
  66767. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  66768. return bits;
  66769. }
  66770. bits |= ((e - 112) << 10) | (m >> 1);
  66771. bits += m & 1;
  66772. return bits;
  66773. };
  66774. DDSTools._FromHalfFloat = function (value) {
  66775. var s = (value & 0x8000) >> 15;
  66776. var e = (value & 0x7C00) >> 10;
  66777. var f = value & 0x03FF;
  66778. if (e === 0) {
  66779. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  66780. }
  66781. else if (e == 0x1F) {
  66782. return f ? NaN : ((s ? -1 : 1) * Infinity);
  66783. }
  66784. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  66785. };
  66786. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66787. var destArray = new Float32Array(dataLength);
  66788. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66789. var index = 0;
  66790. for (var y = 0; y < height; y++) {
  66791. for (var x = 0; x < width; x++) {
  66792. var srcPos = (x + y * width) * 4;
  66793. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  66794. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  66795. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  66796. if (DDSTools.StoreLODInAlphaChannel) {
  66797. destArray[index + 3] = lod;
  66798. }
  66799. else {
  66800. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  66801. }
  66802. index += 4;
  66803. }
  66804. }
  66805. return destArray;
  66806. };
  66807. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66808. if (DDSTools.StoreLODInAlphaChannel) {
  66809. var destArray = new Uint16Array(dataLength);
  66810. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66811. var index = 0;
  66812. for (var y = 0; y < height; y++) {
  66813. for (var x = 0; x < width; x++) {
  66814. var srcPos = (x + y * width) * 4;
  66815. destArray[index] = srcData[srcPos];
  66816. destArray[index + 1] = srcData[srcPos + 1];
  66817. destArray[index + 2] = srcData[srcPos + 2];
  66818. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  66819. index += 4;
  66820. }
  66821. }
  66822. return destArray;
  66823. }
  66824. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  66825. };
  66826. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66827. if (DDSTools.StoreLODInAlphaChannel) {
  66828. var destArray = new Float32Array(dataLength);
  66829. var srcData = new Float32Array(arrayBuffer, dataOffset);
  66830. var index = 0;
  66831. for (var y = 0; y < height; y++) {
  66832. for (var x = 0; x < width; x++) {
  66833. var srcPos = (x + y * width) * 4;
  66834. destArray[index] = srcData[srcPos];
  66835. destArray[index + 1] = srcData[srcPos + 1];
  66836. destArray[index + 2] = srcData[srcPos + 2];
  66837. destArray[index + 3] = lod;
  66838. index += 4;
  66839. }
  66840. }
  66841. return destArray;
  66842. }
  66843. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  66844. };
  66845. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66846. var destArray = new Uint8Array(dataLength);
  66847. var srcData = new Float32Array(arrayBuffer, dataOffset);
  66848. var index = 0;
  66849. for (var y = 0; y < height; y++) {
  66850. for (var x = 0; x < width; x++) {
  66851. var srcPos = (x + y * width) * 4;
  66852. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  66853. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  66854. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  66855. if (DDSTools.StoreLODInAlphaChannel) {
  66856. destArray[index + 3] = lod;
  66857. }
  66858. else {
  66859. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  66860. }
  66861. index += 4;
  66862. }
  66863. }
  66864. return destArray;
  66865. };
  66866. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66867. var destArray = new Uint8Array(dataLength);
  66868. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66869. var index = 0;
  66870. for (var y = 0; y < height; y++) {
  66871. for (var x = 0; x < width; x++) {
  66872. var srcPos = (x + y * width) * 4;
  66873. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  66874. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  66875. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  66876. if (DDSTools.StoreLODInAlphaChannel) {
  66877. destArray[index + 3] = lod;
  66878. }
  66879. else {
  66880. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  66881. }
  66882. index += 4;
  66883. }
  66884. }
  66885. return destArray;
  66886. };
  66887. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  66888. var byteArray = new Uint8Array(dataLength);
  66889. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  66890. var index = 0;
  66891. for (var y = 0; y < height; y++) {
  66892. for (var x = 0; x < width; x++) {
  66893. var srcPos = (x + y * width) * 4;
  66894. byteArray[index] = srcData[srcPos + 2];
  66895. byteArray[index + 1] = srcData[srcPos + 1];
  66896. byteArray[index + 2] = srcData[srcPos];
  66897. byteArray[index + 3] = srcData[srcPos + 3];
  66898. index += 4;
  66899. }
  66900. }
  66901. return byteArray;
  66902. };
  66903. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  66904. var byteArray = new Uint8Array(dataLength);
  66905. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  66906. var index = 0;
  66907. for (var y = 0; y < height; y++) {
  66908. for (var x = 0; x < width; x++) {
  66909. var srcPos = (x + y * width) * 3;
  66910. byteArray[index] = srcData[srcPos + 2];
  66911. byteArray[index + 1] = srcData[srcPos + 1];
  66912. byteArray[index + 2] = srcData[srcPos];
  66913. index += 3;
  66914. }
  66915. }
  66916. return byteArray;
  66917. };
  66918. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  66919. var byteArray = new Uint8Array(dataLength);
  66920. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  66921. var index = 0;
  66922. for (var y = 0; y < height; y++) {
  66923. for (var x = 0; x < width; x++) {
  66924. var srcPos = (x + y * width);
  66925. byteArray[index] = srcData[srcPos];
  66926. index++;
  66927. }
  66928. }
  66929. return byteArray;
  66930. };
  66931. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  66932. if (lodIndex === void 0) { lodIndex = -1; }
  66933. var ext = engine.getCaps().s3tc;
  66934. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  66935. var internalFormat = 0;
  66936. var format = 0;
  66937. var blockBytes = 1;
  66938. if (header[off_magic] != DDS_MAGIC) {
  66939. BABYLON.Tools.Error("Invalid magic number in DDS header");
  66940. return;
  66941. }
  66942. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  66943. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  66944. return;
  66945. }
  66946. if (info.isCompressed && !ext) {
  66947. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  66948. return;
  66949. }
  66950. var bpp = header[off_RGBbpp];
  66951. dataOffset = header[off_size] + 4;
  66952. var computeFormats = false;
  66953. if (info.isFourCC && ext) {
  66954. fourCC = header[off_pfFourCC];
  66955. switch (fourCC) {
  66956. case FOURCC_DXT1:
  66957. blockBytes = 8;
  66958. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  66959. break;
  66960. case FOURCC_DXT3:
  66961. blockBytes = 16;
  66962. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  66963. break;
  66964. case FOURCC_DXT5:
  66965. blockBytes = 16;
  66966. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  66967. break;
  66968. case FOURCC_D3DFMT_R16G16B16A16F:
  66969. computeFormats = true;
  66970. break;
  66971. case FOURCC_D3DFMT_R32G32B32A32F:
  66972. computeFormats = true;
  66973. break;
  66974. case FOURCC_DX10:
  66975. // There is an additionnal header so dataOffset need to be changed
  66976. dataOffset += 5 * 4; // 5 uints
  66977. var supported = false;
  66978. switch (info.dxgiFormat) {
  66979. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  66980. computeFormats = true;
  66981. supported = true;
  66982. break;
  66983. case DXGI_FORMAT_B8G8R8X8_UNORM:
  66984. info.isRGB = true;
  66985. info.isFourCC = false;
  66986. bpp = 32;
  66987. supported = true;
  66988. break;
  66989. }
  66990. if (supported) {
  66991. break;
  66992. }
  66993. default:
  66994. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  66995. return;
  66996. }
  66997. }
  66998. if (computeFormats) {
  66999. format = engine._getWebGLTextureType(info.textureType);
  67000. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67001. }
  67002. mipmapCount = 1;
  67003. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67004. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67005. }
  67006. for (var face = 0; face < faces; face++) {
  67007. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67008. width = header[off_width];
  67009. height = header[off_height];
  67010. for (mip = 0; mip < mipmapCount; ++mip) {
  67011. if (lodIndex === -1 || lodIndex === mip) {
  67012. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67013. var i = (lodIndex === -1) ? mip : 0;
  67014. if (!info.isCompressed && info.isFourCC) {
  67015. dataLength = width * height * 4;
  67016. var FloatArray = null;
  67017. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67018. if (bpp === 128) {
  67019. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67020. }
  67021. else if (bpp === 64) {
  67022. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67023. }
  67024. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67025. format = engine._getWebGLTextureType(info.textureType);
  67026. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67027. }
  67028. else {
  67029. if (bpp === 128) {
  67030. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67031. }
  67032. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67033. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67034. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67035. format = engine._getWebGLTextureType(info.textureType);
  67036. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67037. }
  67038. else {
  67039. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67040. }
  67041. }
  67042. if (FloatArray) {
  67043. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67044. }
  67045. }
  67046. else if (info.isRGB) {
  67047. if (bpp === 24) {
  67048. dataLength = width * height * 3;
  67049. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67050. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67051. }
  67052. else {
  67053. dataLength = width * height * 4;
  67054. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67055. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67056. }
  67057. }
  67058. else if (info.isLuminance) {
  67059. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67060. var unpaddedRowSize = width;
  67061. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67062. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67063. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67064. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67065. }
  67066. else {
  67067. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67068. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67069. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67070. }
  67071. }
  67072. dataOffset += width * height * (bpp / 8);
  67073. width *= 0.5;
  67074. height *= 0.5;
  67075. width = Math.max(1.0, width);
  67076. height = Math.max(1.0, height);
  67077. }
  67078. }
  67079. };
  67080. DDSTools.StoreLODInAlphaChannel = false;
  67081. return DDSTools;
  67082. }());
  67083. Internals.DDSTools = DDSTools;
  67084. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67085. })(BABYLON || (BABYLON = {}));
  67086. //# sourceMappingURL=babylon.dds.js.map
  67087. var BABYLON;
  67088. (function (BABYLON) {
  67089. var Internals;
  67090. (function (Internals) {
  67091. /**
  67092. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67093. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67094. */
  67095. var KhronosTextureContainer = /** @class */ (function () {
  67096. /**
  67097. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67098. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67099. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67100. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67101. */
  67102. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67103. this.arrayBuffer = arrayBuffer;
  67104. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67105. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67106. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67107. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67108. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67109. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67110. BABYLON.Tools.Error("texture missing KTX identifier");
  67111. return;
  67112. }
  67113. // load the reset of the header in native 32 bit int
  67114. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67115. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67116. var oppositeEndianess = header[0] === 0x01020304;
  67117. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67118. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67119. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67120. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67121. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67122. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67123. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67124. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67125. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67126. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67127. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67128. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67129. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67130. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67131. if (this.glType !== 0) {
  67132. BABYLON.Tools.Error("only compressed formats currently supported");
  67133. return;
  67134. }
  67135. else {
  67136. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67137. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67138. }
  67139. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67140. BABYLON.Tools.Error("only 2D textures currently supported");
  67141. return;
  67142. }
  67143. if (this.numberOfArrayElements !== 0) {
  67144. BABYLON.Tools.Error("texture arrays not currently supported");
  67145. return;
  67146. }
  67147. if (this.numberOfFaces !== facesExpected) {
  67148. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67149. return;
  67150. }
  67151. // we now have a completely validated file, so could use existence of loadType as success
  67152. // would need to make this more elaborate & adjust checks above to support more than one load type
  67153. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67154. }
  67155. // not as fast hardware based, but will probably never need to use
  67156. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67157. return ((val & 0xFF) << 24)
  67158. | ((val & 0xFF00) << 8)
  67159. | ((val >> 8) & 0xFF00)
  67160. | ((val >> 24) & 0xFF);
  67161. };
  67162. /**
  67163. * It is assumed that the texture has already been created & is currently bound
  67164. */
  67165. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67166. switch (this.loadType) {
  67167. case KhronosTextureContainer.COMPRESSED_2D:
  67168. this._upload2DCompressedLevels(gl, loadMipmaps);
  67169. break;
  67170. case KhronosTextureContainer.TEX_2D:
  67171. case KhronosTextureContainer.COMPRESSED_3D:
  67172. case KhronosTextureContainer.TEX_3D:
  67173. }
  67174. };
  67175. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67176. // initialize width & height for level 1
  67177. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67178. var width = this.pixelWidth;
  67179. var height = this.pixelHeight;
  67180. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67181. for (var level = 0; level < mipmapCount; level++) {
  67182. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67183. for (var face = 0; face < this.numberOfFaces; face++) {
  67184. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67185. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67186. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67187. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67188. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67189. }
  67190. width = Math.max(1.0, width * 0.5);
  67191. height = Math.max(1.0, height * 0.5);
  67192. }
  67193. };
  67194. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67195. // load types
  67196. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67197. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67198. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67199. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67200. return KhronosTextureContainer;
  67201. }());
  67202. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67203. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67204. })(BABYLON || (BABYLON = {}));
  67205. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67206. var BABYLON;
  67207. (function (BABYLON) {
  67208. var Debug;
  67209. (function (Debug) {
  67210. /**
  67211. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67212. */
  67213. var SkeletonViewer = /** @class */ (function () {
  67214. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67215. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67216. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67217. this.skeleton = skeleton;
  67218. this.mesh = mesh;
  67219. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67220. this.renderingGroupId = renderingGroupId;
  67221. this.color = BABYLON.Color3.White();
  67222. this._debugLines = new Array();
  67223. this._isEnabled = false;
  67224. this._scene = scene;
  67225. this.update();
  67226. this._renderFunction = this.update.bind(this);
  67227. }
  67228. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67229. get: function () {
  67230. return this._isEnabled;
  67231. },
  67232. set: function (value) {
  67233. if (this._isEnabled === value) {
  67234. return;
  67235. }
  67236. this._isEnabled = value;
  67237. if (value) {
  67238. this._scene.registerBeforeRender(this._renderFunction);
  67239. }
  67240. else {
  67241. this._scene.unregisterBeforeRender(this._renderFunction);
  67242. }
  67243. },
  67244. enumerable: true,
  67245. configurable: true
  67246. });
  67247. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67248. if (x === void 0) { x = 0; }
  67249. if (y === void 0) { y = 0; }
  67250. if (z === void 0) { z = 0; }
  67251. var tmat = BABYLON.Tmp.Matrix[0];
  67252. var parentBone = bone.getParent();
  67253. tmat.copyFrom(bone.getLocalMatrix());
  67254. if (x !== 0 || y !== 0 || z !== 0) {
  67255. var tmat2 = BABYLON.Tmp.Matrix[1];
  67256. BABYLON.Matrix.IdentityToRef(tmat2);
  67257. tmat2.m[12] = x;
  67258. tmat2.m[13] = y;
  67259. tmat2.m[14] = z;
  67260. tmat2.multiplyToRef(tmat, tmat);
  67261. }
  67262. if (parentBone) {
  67263. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67264. }
  67265. tmat.multiplyToRef(meshMat, tmat);
  67266. position.x = tmat.m[12];
  67267. position.y = tmat.m[13];
  67268. position.z = tmat.m[14];
  67269. };
  67270. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67271. var len = bones.length;
  67272. var meshPos = this.mesh.position;
  67273. for (var i = 0; i < len; i++) {
  67274. var bone = bones[i];
  67275. var points = this._debugLines[i];
  67276. if (!points) {
  67277. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67278. this._debugLines[i] = points;
  67279. }
  67280. this._getBonePosition(points[0], bone, meshMat);
  67281. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67282. points[0].subtractInPlace(meshPos);
  67283. points[1].subtractInPlace(meshPos);
  67284. }
  67285. };
  67286. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67287. var len = bones.length;
  67288. var boneNum = 0;
  67289. var meshPos = this.mesh.position;
  67290. for (var i = len - 1; i >= 0; i--) {
  67291. var childBone = bones[i];
  67292. var parentBone = childBone.getParent();
  67293. if (!parentBone) {
  67294. continue;
  67295. }
  67296. var points = this._debugLines[boneNum];
  67297. if (!points) {
  67298. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67299. this._debugLines[boneNum] = points;
  67300. }
  67301. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67302. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67303. points[0].subtractInPlace(meshPos);
  67304. points[1].subtractInPlace(meshPos);
  67305. boneNum++;
  67306. }
  67307. };
  67308. SkeletonViewer.prototype.update = function () {
  67309. if (this.autoUpdateBonesMatrices) {
  67310. this.skeleton.computeAbsoluteTransforms();
  67311. }
  67312. if (this.skeleton.bones[0].length === undefined) {
  67313. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67314. }
  67315. else {
  67316. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67317. }
  67318. if (!this._debugMesh) {
  67319. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67320. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67321. }
  67322. else {
  67323. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67324. }
  67325. this._debugMesh.position.copyFrom(this.mesh.position);
  67326. this._debugMesh.color = this.color;
  67327. };
  67328. SkeletonViewer.prototype.dispose = function () {
  67329. if (this._debugMesh) {
  67330. this.isEnabled = false;
  67331. this._debugMesh.dispose();
  67332. this._debugMesh = null;
  67333. }
  67334. };
  67335. return SkeletonViewer;
  67336. }());
  67337. Debug.SkeletonViewer = SkeletonViewer;
  67338. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67339. })(BABYLON || (BABYLON = {}));
  67340. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67341. var BABYLON;
  67342. (function (BABYLON) {
  67343. var Debug;
  67344. (function (Debug) {
  67345. var AxesViewer = /** @class */ (function () {
  67346. function AxesViewer(scene, scaleLines) {
  67347. if (scaleLines === void 0) { scaleLines = 1; }
  67348. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67349. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67350. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67351. this.scaleLines = 1;
  67352. this.scaleLines = scaleLines;
  67353. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67354. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67355. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67356. this._xmesh.renderingGroupId = 2;
  67357. this._ymesh.renderingGroupId = 2;
  67358. this._zmesh.renderingGroupId = 2;
  67359. this._xmesh.material.checkReadyOnlyOnce = true;
  67360. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67361. this._ymesh.material.checkReadyOnlyOnce = true;
  67362. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67363. this._zmesh.material.checkReadyOnlyOnce = true;
  67364. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67365. this.scene = scene;
  67366. }
  67367. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67368. var scaleLines = this.scaleLines;
  67369. if (this._xmesh) {
  67370. this._xmesh.position.copyFrom(position);
  67371. }
  67372. if (this._ymesh) {
  67373. this._ymesh.position.copyFrom(position);
  67374. }
  67375. if (this._zmesh) {
  67376. this._zmesh.position.copyFrom(position);
  67377. }
  67378. var point2 = this._xline[1];
  67379. point2.x = xaxis.x * scaleLines;
  67380. point2.y = xaxis.y * scaleLines;
  67381. point2.z = xaxis.z * scaleLines;
  67382. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67383. point2 = this._yline[1];
  67384. point2.x = yaxis.x * scaleLines;
  67385. point2.y = yaxis.y * scaleLines;
  67386. point2.z = yaxis.z * scaleLines;
  67387. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67388. point2 = this._zline[1];
  67389. point2.x = zaxis.x * scaleLines;
  67390. point2.y = zaxis.y * scaleLines;
  67391. point2.z = zaxis.z * scaleLines;
  67392. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67393. };
  67394. AxesViewer.prototype.dispose = function () {
  67395. if (this._xmesh) {
  67396. this._xmesh.dispose();
  67397. }
  67398. if (this._ymesh) {
  67399. this._ymesh.dispose();
  67400. }
  67401. if (this._zmesh) {
  67402. this._zmesh.dispose();
  67403. }
  67404. this._xmesh = null;
  67405. this._ymesh = null;
  67406. this._zmesh = null;
  67407. this.scene = null;
  67408. };
  67409. return AxesViewer;
  67410. }());
  67411. Debug.AxesViewer = AxesViewer;
  67412. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67413. })(BABYLON || (BABYLON = {}));
  67414. //# sourceMappingURL=babylon.axesViewer.js.map
  67415. var BABYLON;
  67416. (function (BABYLON) {
  67417. var Debug;
  67418. (function (Debug) {
  67419. var BoneAxesViewer = /** @class */ (function (_super) {
  67420. __extends(BoneAxesViewer, _super);
  67421. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67422. if (scaleLines === void 0) { scaleLines = 1; }
  67423. var _this = _super.call(this, scene, scaleLines) || this;
  67424. _this.pos = BABYLON.Vector3.Zero();
  67425. _this.xaxis = BABYLON.Vector3.Zero();
  67426. _this.yaxis = BABYLON.Vector3.Zero();
  67427. _this.zaxis = BABYLON.Vector3.Zero();
  67428. _this.mesh = mesh;
  67429. _this.bone = bone;
  67430. return _this;
  67431. }
  67432. BoneAxesViewer.prototype.update = function () {
  67433. if (!this.mesh || !this.bone) {
  67434. return;
  67435. }
  67436. var bone = this.bone;
  67437. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67438. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67439. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67440. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67441. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67442. };
  67443. BoneAxesViewer.prototype.dispose = function () {
  67444. if (this.mesh) {
  67445. this.mesh = null;
  67446. this.bone = null;
  67447. _super.prototype.dispose.call(this);
  67448. }
  67449. };
  67450. return BoneAxesViewer;
  67451. }(Debug.AxesViewer));
  67452. Debug.BoneAxesViewer = BoneAxesViewer;
  67453. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67454. })(BABYLON || (BABYLON = {}));
  67455. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67456. var BABYLON;
  67457. (function (BABYLON) {
  67458. var RayHelper = /** @class */ (function () {
  67459. function RayHelper(ray) {
  67460. this.ray = ray;
  67461. }
  67462. RayHelper.CreateAndShow = function (ray, scene, color) {
  67463. var helper = new RayHelper(ray);
  67464. helper.show(scene, color);
  67465. return helper;
  67466. };
  67467. RayHelper.prototype.show = function (scene, color) {
  67468. if (!this._renderFunction && this.ray) {
  67469. var ray = this.ray;
  67470. this._renderFunction = this._render.bind(this);
  67471. this._scene = scene;
  67472. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  67473. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  67474. if (this._renderFunction) {
  67475. this._scene.registerBeforeRender(this._renderFunction);
  67476. }
  67477. }
  67478. if (color && this._renderLine) {
  67479. this._renderLine.color.copyFrom(color);
  67480. }
  67481. };
  67482. RayHelper.prototype.hide = function () {
  67483. if (this._renderFunction && this._scene) {
  67484. this._scene.unregisterBeforeRender(this._renderFunction);
  67485. this._scene = null;
  67486. this._renderFunction = null;
  67487. if (this._renderLine) {
  67488. this._renderLine.dispose();
  67489. this._renderLine = null;
  67490. }
  67491. this._renderPoints = [];
  67492. }
  67493. };
  67494. RayHelper.prototype._render = function () {
  67495. var ray = this.ray;
  67496. if (!ray) {
  67497. return;
  67498. }
  67499. var point = this._renderPoints[1];
  67500. var len = Math.min(ray.length, 1000000);
  67501. point.copyFrom(ray.direction);
  67502. point.scaleInPlace(len);
  67503. point.addInPlace(ray.origin);
  67504. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  67505. };
  67506. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  67507. this._attachedToMesh = mesh;
  67508. var ray = this.ray;
  67509. if (!ray) {
  67510. return;
  67511. }
  67512. if (!ray.direction) {
  67513. ray.direction = BABYLON.Vector3.Zero();
  67514. }
  67515. if (!ray.origin) {
  67516. ray.origin = BABYLON.Vector3.Zero();
  67517. }
  67518. if (length) {
  67519. ray.length = length;
  67520. }
  67521. if (!meshSpaceOrigin) {
  67522. meshSpaceOrigin = BABYLON.Vector3.Zero();
  67523. }
  67524. if (!meshSpaceDirection) {
  67525. // -1 so that this will work with Mesh.lookAt
  67526. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  67527. }
  67528. if (!this._meshSpaceDirection) {
  67529. this._meshSpaceDirection = meshSpaceDirection.clone();
  67530. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  67531. }
  67532. else {
  67533. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  67534. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  67535. }
  67536. if (!this._updateToMeshFunction) {
  67537. this._updateToMeshFunction = this._updateToMesh.bind(this);
  67538. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  67539. }
  67540. this._updateToMesh();
  67541. };
  67542. RayHelper.prototype.detachFromMesh = function () {
  67543. if (this._attachedToMesh) {
  67544. if (this._updateToMeshFunction) {
  67545. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  67546. }
  67547. this._attachedToMesh = null;
  67548. this._updateToMeshFunction = null;
  67549. }
  67550. };
  67551. RayHelper.prototype._updateToMesh = function () {
  67552. var ray = this.ray;
  67553. if (!this._attachedToMesh || !ray) {
  67554. return;
  67555. }
  67556. if (this._attachedToMesh._isDisposed) {
  67557. this.detachFromMesh();
  67558. return;
  67559. }
  67560. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  67561. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  67562. };
  67563. RayHelper.prototype.dispose = function () {
  67564. this.hide();
  67565. this.detachFromMesh();
  67566. this.ray = null;
  67567. };
  67568. return RayHelper;
  67569. }());
  67570. BABYLON.RayHelper = RayHelper;
  67571. })(BABYLON || (BABYLON = {}));
  67572. //# sourceMappingURL=babylon.rayHelper.js.map
  67573. var BABYLON;
  67574. (function (BABYLON) {
  67575. var DebugLayer = /** @class */ (function () {
  67576. function DebugLayer(scene) {
  67577. this._scene = scene;
  67578. }
  67579. /** Creates the inspector window. */
  67580. DebugLayer.prototype._createInspector = function (config) {
  67581. if (config === void 0) { config = {}; }
  67582. var popup = config.popup || false;
  67583. var initialTab = config.initialTab || 0;
  67584. var parentElement = config.parentElement || null;
  67585. if (!this._inspector) {
  67586. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  67587. } // else nothing to do,; instance is already existing
  67588. };
  67589. DebugLayer.prototype.isVisible = function () {
  67590. if (!this._inspector) {
  67591. return false;
  67592. }
  67593. return true;
  67594. };
  67595. DebugLayer.prototype.hide = function () {
  67596. if (this._inspector) {
  67597. try {
  67598. this._inspector.dispose();
  67599. }
  67600. catch (e) {
  67601. // If the inspector has been removed directly from the inspector tool
  67602. }
  67603. this._inspector = null;
  67604. }
  67605. };
  67606. DebugLayer.prototype.show = function (config) {
  67607. if (config === void 0) { config = {}; }
  67608. if (typeof INSPECTOR == 'undefined') {
  67609. // Load inspector and add it to the DOM
  67610. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  67611. }
  67612. else {
  67613. // Otherwise creates the inspector
  67614. this._createInspector(config);
  67615. }
  67616. };
  67617. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  67618. return DebugLayer;
  67619. }());
  67620. BABYLON.DebugLayer = DebugLayer;
  67621. })(BABYLON || (BABYLON = {}));
  67622. //# sourceMappingURL=babylon.debugLayer.js.map
  67623. var BABYLON;
  67624. (function (BABYLON) {
  67625. var Debug;
  67626. (function (Debug) {
  67627. var PhysicsViewer = /** @class */ (function () {
  67628. function PhysicsViewer(scene) {
  67629. this._impostors = [];
  67630. this._meshes = [];
  67631. this._numMeshes = 0;
  67632. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67633. var physicEngine = this._scene.getPhysicsEngine();
  67634. if (physicEngine) {
  67635. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  67636. }
  67637. }
  67638. PhysicsViewer.prototype._updateDebugMeshes = function () {
  67639. var plugin = this._physicsEnginePlugin;
  67640. for (var i = 0; i < this._numMeshes; i++) {
  67641. var impostor = this._impostors[i];
  67642. if (!impostor) {
  67643. continue;
  67644. }
  67645. if (impostor.isDisposed) {
  67646. this.hideImpostor(this._impostors[i--]);
  67647. }
  67648. else {
  67649. var mesh = this._meshes[i];
  67650. if (mesh && plugin) {
  67651. plugin.syncMeshWithImpostor(mesh, impostor);
  67652. }
  67653. }
  67654. }
  67655. };
  67656. PhysicsViewer.prototype.showImpostor = function (impostor) {
  67657. if (!this._scene) {
  67658. return;
  67659. }
  67660. for (var i = 0; i < this._numMeshes; i++) {
  67661. if (this._impostors[i] == impostor) {
  67662. return;
  67663. }
  67664. }
  67665. var debugMesh = this._getDebugMesh(impostor, this._scene);
  67666. if (debugMesh) {
  67667. this._impostors[this._numMeshes] = impostor;
  67668. this._meshes[this._numMeshes] = debugMesh;
  67669. if (this._numMeshes === 0) {
  67670. this._renderFunction = this._updateDebugMeshes.bind(this);
  67671. this._scene.registerBeforeRender(this._renderFunction);
  67672. }
  67673. this._numMeshes++;
  67674. }
  67675. };
  67676. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  67677. if (!impostor || !this._scene) {
  67678. return;
  67679. }
  67680. var removed = false;
  67681. for (var i = 0; i < this._numMeshes; i++) {
  67682. if (this._impostors[i] == impostor) {
  67683. var mesh = this._meshes[i];
  67684. if (!mesh) {
  67685. continue;
  67686. }
  67687. this._scene.removeMesh(mesh);
  67688. mesh.dispose();
  67689. this._numMeshes--;
  67690. if (this._numMeshes > 0) {
  67691. this._meshes[i] = this._meshes[this._numMeshes];
  67692. this._impostors[i] = this._impostors[this._numMeshes];
  67693. this._meshes[this._numMeshes] = null;
  67694. this._impostors[this._numMeshes] = null;
  67695. }
  67696. else {
  67697. this._meshes[0] = null;
  67698. this._impostors[0] = null;
  67699. }
  67700. removed = true;
  67701. break;
  67702. }
  67703. }
  67704. if (removed && this._numMeshes === 0) {
  67705. this._scene.unregisterBeforeRender(this._renderFunction);
  67706. }
  67707. };
  67708. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  67709. if (!this._debugMaterial) {
  67710. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  67711. this._debugMaterial.wireframe = true;
  67712. }
  67713. return this._debugMaterial;
  67714. };
  67715. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  67716. if (!this._debugBoxMesh) {
  67717. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  67718. this._debugBoxMesh.renderingGroupId = 1;
  67719. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67720. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  67721. scene.removeMesh(this._debugBoxMesh);
  67722. }
  67723. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  67724. };
  67725. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  67726. if (!this._debugSphereMesh) {
  67727. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  67728. this._debugSphereMesh.renderingGroupId = 1;
  67729. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67730. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  67731. scene.removeMesh(this._debugSphereMesh);
  67732. }
  67733. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  67734. };
  67735. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  67736. var mesh = null;
  67737. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  67738. mesh = this._getDebugBoxMesh(scene);
  67739. impostor.getBoxSizeToRef(mesh.scaling);
  67740. }
  67741. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  67742. mesh = this._getDebugSphereMesh(scene);
  67743. var radius = impostor.getRadius();
  67744. mesh.scaling.x = radius * 2;
  67745. mesh.scaling.y = radius * 2;
  67746. mesh.scaling.z = radius * 2;
  67747. }
  67748. return mesh;
  67749. };
  67750. PhysicsViewer.prototype.dispose = function () {
  67751. for (var i = 0; i < this._numMeshes; i++) {
  67752. this.hideImpostor(this._impostors[i]);
  67753. }
  67754. if (this._debugBoxMesh) {
  67755. this._debugBoxMesh.dispose();
  67756. }
  67757. if (this._debugSphereMesh) {
  67758. this._debugSphereMesh.dispose();
  67759. }
  67760. if (this._debugMaterial) {
  67761. this._debugMaterial.dispose();
  67762. }
  67763. this._impostors.length = 0;
  67764. this._scene = null;
  67765. this._physicsEnginePlugin = null;
  67766. };
  67767. return PhysicsViewer;
  67768. }());
  67769. Debug.PhysicsViewer = PhysicsViewer;
  67770. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67771. })(BABYLON || (BABYLON = {}));
  67772. //# sourceMappingURL=babylon.physicsViewer.js.map
  67773. var BABYLON;
  67774. (function (BABYLON) {
  67775. var BoundingBoxRenderer = /** @class */ (function () {
  67776. function BoundingBoxRenderer(scene) {
  67777. this.frontColor = new BABYLON.Color3(1, 1, 1);
  67778. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  67779. this.showBackLines = true;
  67780. this.renderList = new BABYLON.SmartArray(32);
  67781. this._vertexBuffers = {};
  67782. this._scene = scene;
  67783. }
  67784. BoundingBoxRenderer.prototype._prepareRessources = function () {
  67785. if (this._colorShader) {
  67786. return;
  67787. }
  67788. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  67789. attributes: [BABYLON.VertexBuffer.PositionKind],
  67790. uniforms: ["world", "viewProjection", "color"]
  67791. });
  67792. var engine = this._scene.getEngine();
  67793. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  67794. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  67795. this._createIndexBuffer();
  67796. };
  67797. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  67798. var engine = this._scene.getEngine();
  67799. 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]);
  67800. };
  67801. BoundingBoxRenderer.prototype._rebuild = function () {
  67802. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67803. if (vb) {
  67804. vb._rebuild();
  67805. }
  67806. this._createIndexBuffer();
  67807. };
  67808. BoundingBoxRenderer.prototype.reset = function () {
  67809. this.renderList.reset();
  67810. };
  67811. BoundingBoxRenderer.prototype.render = function () {
  67812. if (this.renderList.length === 0) {
  67813. return;
  67814. }
  67815. this._prepareRessources();
  67816. if (!this._colorShader.isReady()) {
  67817. return;
  67818. }
  67819. var engine = this._scene.getEngine();
  67820. engine.setDepthWrite(false);
  67821. this._colorShader._preBind();
  67822. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  67823. var boundingBox = this.renderList.data[boundingBoxIndex];
  67824. var min = boundingBox.minimum;
  67825. var max = boundingBox.maximum;
  67826. var diff = max.subtract(min);
  67827. var median = min.add(diff.scale(0.5));
  67828. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  67829. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  67830. .multiply(boundingBox.getWorldMatrix());
  67831. // VBOs
  67832. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  67833. if (this.showBackLines) {
  67834. // Back
  67835. engine.setDepthFunctionToGreaterOrEqual();
  67836. this._scene.resetCachedMaterial();
  67837. this._colorShader.setColor4("color", this.backColor.toColor4());
  67838. this._colorShader.bind(worldMatrix);
  67839. // Draw order
  67840. engine.draw(false, 0, 24);
  67841. }
  67842. // Front
  67843. engine.setDepthFunctionToLess();
  67844. this._scene.resetCachedMaterial();
  67845. this._colorShader.setColor4("color", this.frontColor.toColor4());
  67846. this._colorShader.bind(worldMatrix);
  67847. // Draw order
  67848. engine.draw(false, 0, 24);
  67849. }
  67850. this._colorShader.unbind();
  67851. engine.setDepthFunctionToLessOrEqual();
  67852. engine.setDepthWrite(true);
  67853. };
  67854. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  67855. this._prepareRessources();
  67856. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  67857. return;
  67858. }
  67859. var engine = this._scene.getEngine();
  67860. engine.setDepthWrite(false);
  67861. engine.setColorWrite(false);
  67862. this._colorShader._preBind();
  67863. var boundingBox = mesh._boundingInfo.boundingBox;
  67864. var min = boundingBox.minimum;
  67865. var max = boundingBox.maximum;
  67866. var diff = max.subtract(min);
  67867. var median = min.add(diff.scale(0.5));
  67868. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  67869. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  67870. .multiply(boundingBox.getWorldMatrix());
  67871. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  67872. engine.setDepthFunctionToLess();
  67873. this._scene.resetCachedMaterial();
  67874. this._colorShader.bind(worldMatrix);
  67875. engine.draw(false, 0, 24);
  67876. this._colorShader.unbind();
  67877. engine.setDepthFunctionToLessOrEqual();
  67878. engine.setDepthWrite(true);
  67879. engine.setColorWrite(true);
  67880. };
  67881. BoundingBoxRenderer.prototype.dispose = function () {
  67882. if (!this._colorShader) {
  67883. return;
  67884. }
  67885. this.renderList.dispose();
  67886. this._colorShader.dispose();
  67887. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67888. if (buffer) {
  67889. buffer.dispose();
  67890. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67891. }
  67892. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67893. };
  67894. return BoundingBoxRenderer;
  67895. }());
  67896. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  67897. })(BABYLON || (BABYLON = {}));
  67898. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  67899. var BABYLON;
  67900. (function (BABYLON) {
  67901. var MorphTarget = /** @class */ (function () {
  67902. function MorphTarget(name, influence) {
  67903. if (influence === void 0) { influence = 0; }
  67904. this.name = name;
  67905. this.animations = new Array();
  67906. this.onInfluenceChanged = new BABYLON.Observable();
  67907. this.influence = influence;
  67908. }
  67909. Object.defineProperty(MorphTarget.prototype, "influence", {
  67910. get: function () {
  67911. return this._influence;
  67912. },
  67913. set: function (influence) {
  67914. if (this._influence === influence) {
  67915. return;
  67916. }
  67917. var previous = this._influence;
  67918. this._influence = influence;
  67919. if (this.onInfluenceChanged.hasObservers) {
  67920. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  67921. }
  67922. },
  67923. enumerable: true,
  67924. configurable: true
  67925. });
  67926. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  67927. get: function () {
  67928. return this._normals !== undefined;
  67929. },
  67930. enumerable: true,
  67931. configurable: true
  67932. });
  67933. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  67934. get: function () {
  67935. return this._tangents !== undefined;
  67936. },
  67937. enumerable: true,
  67938. configurable: true
  67939. });
  67940. MorphTarget.prototype.setPositions = function (data) {
  67941. this._positions = new Float32Array(data);
  67942. };
  67943. MorphTarget.prototype.getPositions = function () {
  67944. return this._positions;
  67945. };
  67946. MorphTarget.prototype.setNormals = function (data) {
  67947. this._normals = new Float32Array(data);
  67948. };
  67949. MorphTarget.prototype.getNormals = function () {
  67950. return this._normals;
  67951. };
  67952. MorphTarget.prototype.setTangents = function (data) {
  67953. this._tangents = new Float32Array(data);
  67954. };
  67955. MorphTarget.prototype.getTangents = function () {
  67956. return this._tangents;
  67957. };
  67958. /**
  67959. * Serializes the current target into a Serialization object.
  67960. * Returns the serialized object.
  67961. */
  67962. MorphTarget.prototype.serialize = function () {
  67963. var serializationObject = {};
  67964. serializationObject.name = this.name;
  67965. serializationObject.influence = this.influence;
  67966. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  67967. if (this.hasNormals) {
  67968. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  67969. }
  67970. if (this.hasTangents) {
  67971. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  67972. }
  67973. // Animations
  67974. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  67975. return serializationObject;
  67976. };
  67977. // Statics
  67978. MorphTarget.Parse = function (serializationObject) {
  67979. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  67980. result.setPositions(serializationObject.positions);
  67981. if (serializationObject.normals) {
  67982. result.setNormals(serializationObject.normals);
  67983. }
  67984. if (serializationObject.tangents) {
  67985. result.setTangents(serializationObject.tangents);
  67986. }
  67987. // Animations
  67988. if (serializationObject.animations) {
  67989. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  67990. var parsedAnimation = serializationObject.animations[animationIndex];
  67991. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67992. }
  67993. }
  67994. return result;
  67995. };
  67996. MorphTarget.FromMesh = function (mesh, name, influence) {
  67997. if (!name) {
  67998. name = mesh.name;
  67999. }
  68000. var result = new MorphTarget(name, influence);
  68001. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68002. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68003. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68004. }
  68005. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68006. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68007. }
  68008. return result;
  68009. };
  68010. return MorphTarget;
  68011. }());
  68012. BABYLON.MorphTarget = MorphTarget;
  68013. })(BABYLON || (BABYLON = {}));
  68014. //# sourceMappingURL=babylon.morphTarget.js.map
  68015. var BABYLON;
  68016. (function (BABYLON) {
  68017. var MorphTargetManager = /** @class */ (function () {
  68018. function MorphTargetManager(scene) {
  68019. if (scene === void 0) { scene = null; }
  68020. this._targets = new Array();
  68021. this._targetObservable = new Array();
  68022. this._activeTargets = new BABYLON.SmartArray(16);
  68023. this._supportsNormals = false;
  68024. this._supportsTangents = false;
  68025. this._vertexCount = 0;
  68026. this._uniqueId = 0;
  68027. this._tempInfluences = new Array();
  68028. if (!scene) {
  68029. scene = BABYLON.Engine.LastCreatedScene;
  68030. }
  68031. this._scene = scene;
  68032. if (this._scene) {
  68033. this._scene.morphTargetManagers.push(this);
  68034. this._uniqueId = this._scene.getUniqueId();
  68035. }
  68036. }
  68037. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68038. get: function () {
  68039. return this._uniqueId;
  68040. },
  68041. enumerable: true,
  68042. configurable: true
  68043. });
  68044. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68045. get: function () {
  68046. return this._vertexCount;
  68047. },
  68048. enumerable: true,
  68049. configurable: true
  68050. });
  68051. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68052. get: function () {
  68053. return this._supportsNormals;
  68054. },
  68055. enumerable: true,
  68056. configurable: true
  68057. });
  68058. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68059. get: function () {
  68060. return this._supportsTangents;
  68061. },
  68062. enumerable: true,
  68063. configurable: true
  68064. });
  68065. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68066. get: function () {
  68067. return this._targets.length;
  68068. },
  68069. enumerable: true,
  68070. configurable: true
  68071. });
  68072. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68073. get: function () {
  68074. return this._activeTargets.length;
  68075. },
  68076. enumerable: true,
  68077. configurable: true
  68078. });
  68079. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68080. get: function () {
  68081. return this._influences;
  68082. },
  68083. enumerable: true,
  68084. configurable: true
  68085. });
  68086. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68087. return this._activeTargets.data[index];
  68088. };
  68089. MorphTargetManager.prototype.getTarget = function (index) {
  68090. return this._targets[index];
  68091. };
  68092. MorphTargetManager.prototype.addTarget = function (target) {
  68093. var _this = this;
  68094. if (this._vertexCount) {
  68095. if (this._vertexCount !== target.getPositions().length / 3) {
  68096. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68097. return;
  68098. }
  68099. }
  68100. this._targets.push(target);
  68101. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68102. _this._syncActiveTargets(needUpdate);
  68103. }));
  68104. this._syncActiveTargets(true);
  68105. };
  68106. MorphTargetManager.prototype.removeTarget = function (target) {
  68107. var index = this._targets.indexOf(target);
  68108. if (index >= 0) {
  68109. this._targets.splice(index, 1);
  68110. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68111. this._vertexCount = 0;
  68112. this._syncActiveTargets(true);
  68113. }
  68114. };
  68115. /**
  68116. * Serializes the current manager into a Serialization object.
  68117. * Returns the serialized object.
  68118. */
  68119. MorphTargetManager.prototype.serialize = function () {
  68120. var serializationObject = {};
  68121. serializationObject.id = this.uniqueId;
  68122. serializationObject.targets = [];
  68123. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68124. var target = _a[_i];
  68125. serializationObject.targets.push(target.serialize());
  68126. }
  68127. return serializationObject;
  68128. };
  68129. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68130. var influenceCount = 0;
  68131. this._activeTargets.reset();
  68132. this._supportsNormals = true;
  68133. this._supportsTangents = true;
  68134. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68135. var target = _a[_i];
  68136. if (target.influence > 0) {
  68137. this._activeTargets.push(target);
  68138. this._tempInfluences[influenceCount++] = target.influence;
  68139. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68140. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68141. if (this._vertexCount === 0) {
  68142. this._vertexCount = target.getPositions().length / 3;
  68143. }
  68144. }
  68145. }
  68146. if (!this._influences || this._influences.length !== influenceCount) {
  68147. this._influences = new Float32Array(influenceCount);
  68148. }
  68149. for (var index = 0; index < influenceCount; index++) {
  68150. this._influences[index] = this._tempInfluences[index];
  68151. }
  68152. if (needUpdate && this._scene) {
  68153. // Flag meshes as dirty to resync with the active targets
  68154. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68155. var mesh = _c[_b];
  68156. if (mesh.morphTargetManager === this) {
  68157. mesh._syncGeometryWithMorphTargetManager();
  68158. }
  68159. }
  68160. }
  68161. };
  68162. // Statics
  68163. MorphTargetManager.Parse = function (serializationObject, scene) {
  68164. var result = new MorphTargetManager(scene);
  68165. result._uniqueId = serializationObject.id;
  68166. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68167. var targetData = _a[_i];
  68168. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68169. }
  68170. return result;
  68171. };
  68172. return MorphTargetManager;
  68173. }());
  68174. BABYLON.MorphTargetManager = MorphTargetManager;
  68175. })(BABYLON || (BABYLON = {}));
  68176. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68177. var BABYLON;
  68178. (function (BABYLON) {
  68179. var Octree = /** @class */ (function () {
  68180. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68181. if (maxDepth === void 0) { maxDepth = 2; }
  68182. this.maxDepth = maxDepth;
  68183. this.dynamicContent = new Array();
  68184. this._maxBlockCapacity = maxBlockCapacity || 64;
  68185. this._selectionContent = new BABYLON.SmartArray(1024);
  68186. this._creationFunc = creationFunc;
  68187. }
  68188. // Methods
  68189. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68190. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68191. };
  68192. Octree.prototype.addMesh = function (entry) {
  68193. for (var index = 0; index < this.blocks.length; index++) {
  68194. var block = this.blocks[index];
  68195. block.addEntry(entry);
  68196. }
  68197. };
  68198. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68199. this._selectionContent.reset();
  68200. for (var index = 0; index < this.blocks.length; index++) {
  68201. var block = this.blocks[index];
  68202. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68203. }
  68204. if (allowDuplicate) {
  68205. this._selectionContent.concat(this.dynamicContent);
  68206. }
  68207. else {
  68208. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68209. }
  68210. return this._selectionContent;
  68211. };
  68212. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68213. this._selectionContent.reset();
  68214. for (var index = 0; index < this.blocks.length; index++) {
  68215. var block = this.blocks[index];
  68216. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68217. }
  68218. if (allowDuplicate) {
  68219. this._selectionContent.concat(this.dynamicContent);
  68220. }
  68221. else {
  68222. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68223. }
  68224. return this._selectionContent;
  68225. };
  68226. Octree.prototype.intersectsRay = function (ray) {
  68227. this._selectionContent.reset();
  68228. for (var index = 0; index < this.blocks.length; index++) {
  68229. var block = this.blocks[index];
  68230. block.intersectsRay(ray, this._selectionContent);
  68231. }
  68232. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68233. return this._selectionContent;
  68234. };
  68235. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68236. target.blocks = new Array();
  68237. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68238. // Segmenting space
  68239. for (var x = 0; x < 2; x++) {
  68240. for (var y = 0; y < 2; y++) {
  68241. for (var z = 0; z < 2; z++) {
  68242. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68243. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68244. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68245. block.addEntries(entries);
  68246. target.blocks.push(block);
  68247. }
  68248. }
  68249. }
  68250. };
  68251. Octree.CreationFuncForMeshes = function (entry, block) {
  68252. var boundingInfo = entry.getBoundingInfo();
  68253. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68254. block.entries.push(entry);
  68255. }
  68256. };
  68257. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68258. var boundingInfo = entry.getBoundingInfo();
  68259. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68260. block.entries.push(entry);
  68261. }
  68262. };
  68263. return Octree;
  68264. }());
  68265. BABYLON.Octree = Octree;
  68266. })(BABYLON || (BABYLON = {}));
  68267. //# sourceMappingURL=babylon.octree.js.map
  68268. var BABYLON;
  68269. (function (BABYLON) {
  68270. var OctreeBlock = /** @class */ (function () {
  68271. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68272. this.entries = new Array();
  68273. this._boundingVectors = new Array();
  68274. this._capacity = capacity;
  68275. this._depth = depth;
  68276. this._maxDepth = maxDepth;
  68277. this._creationFunc = creationFunc;
  68278. this._minPoint = minPoint;
  68279. this._maxPoint = maxPoint;
  68280. this._boundingVectors.push(minPoint.clone());
  68281. this._boundingVectors.push(maxPoint.clone());
  68282. this._boundingVectors.push(minPoint.clone());
  68283. this._boundingVectors[2].x = maxPoint.x;
  68284. this._boundingVectors.push(minPoint.clone());
  68285. this._boundingVectors[3].y = maxPoint.y;
  68286. this._boundingVectors.push(minPoint.clone());
  68287. this._boundingVectors[4].z = maxPoint.z;
  68288. this._boundingVectors.push(maxPoint.clone());
  68289. this._boundingVectors[5].z = minPoint.z;
  68290. this._boundingVectors.push(maxPoint.clone());
  68291. this._boundingVectors[6].x = minPoint.x;
  68292. this._boundingVectors.push(maxPoint.clone());
  68293. this._boundingVectors[7].y = minPoint.y;
  68294. }
  68295. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68296. // Property
  68297. get: function () {
  68298. return this._capacity;
  68299. },
  68300. enumerable: true,
  68301. configurable: true
  68302. });
  68303. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68304. get: function () {
  68305. return this._minPoint;
  68306. },
  68307. enumerable: true,
  68308. configurable: true
  68309. });
  68310. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68311. get: function () {
  68312. return this._maxPoint;
  68313. },
  68314. enumerable: true,
  68315. configurable: true
  68316. });
  68317. // Methods
  68318. OctreeBlock.prototype.addEntry = function (entry) {
  68319. if (this.blocks) {
  68320. for (var index = 0; index < this.blocks.length; index++) {
  68321. var block = this.blocks[index];
  68322. block.addEntry(entry);
  68323. }
  68324. return;
  68325. }
  68326. this._creationFunc(entry, this);
  68327. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68328. this.createInnerBlocks();
  68329. }
  68330. };
  68331. OctreeBlock.prototype.addEntries = function (entries) {
  68332. for (var index = 0; index < entries.length; index++) {
  68333. var mesh = entries[index];
  68334. this.addEntry(mesh);
  68335. }
  68336. };
  68337. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68338. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68339. if (this.blocks) {
  68340. for (var index = 0; index < this.blocks.length; index++) {
  68341. var block = this.blocks[index];
  68342. block.select(frustumPlanes, selection, allowDuplicate);
  68343. }
  68344. return;
  68345. }
  68346. if (allowDuplicate) {
  68347. selection.concat(this.entries);
  68348. }
  68349. else {
  68350. selection.concatWithNoDuplicate(this.entries);
  68351. }
  68352. }
  68353. };
  68354. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68355. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68356. if (this.blocks) {
  68357. for (var index = 0; index < this.blocks.length; index++) {
  68358. var block = this.blocks[index];
  68359. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68360. }
  68361. return;
  68362. }
  68363. if (allowDuplicate) {
  68364. selection.concat(this.entries);
  68365. }
  68366. else {
  68367. selection.concatWithNoDuplicate(this.entries);
  68368. }
  68369. }
  68370. };
  68371. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68372. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68373. if (this.blocks) {
  68374. for (var index = 0; index < this.blocks.length; index++) {
  68375. var block = this.blocks[index];
  68376. block.intersectsRay(ray, selection);
  68377. }
  68378. return;
  68379. }
  68380. selection.concatWithNoDuplicate(this.entries);
  68381. }
  68382. };
  68383. OctreeBlock.prototype.createInnerBlocks = function () {
  68384. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68385. };
  68386. return OctreeBlock;
  68387. }());
  68388. BABYLON.OctreeBlock = OctreeBlock;
  68389. })(BABYLON || (BABYLON = {}));
  68390. //# sourceMappingURL=babylon.octreeBlock.js.map
  68391. var BABYLON;
  68392. (function (BABYLON) {
  68393. var SIMDVector3 = /** @class */ (function () {
  68394. function SIMDVector3() {
  68395. }
  68396. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68397. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68398. };
  68399. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68400. var m = transformation.m;
  68401. var m0 = SIMD.Float32x4.load(m, 0);
  68402. var m1 = SIMD.Float32x4.load(m, 4);
  68403. var m2 = SIMD.Float32x4.load(m, 8);
  68404. var m3 = SIMD.Float32x4.load(m, 12);
  68405. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  68406. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68407. result.x = SIMD.Float32x4.extractLane(r, 0);
  68408. result.y = SIMD.Float32x4.extractLane(r, 1);
  68409. result.z = SIMD.Float32x4.extractLane(r, 2);
  68410. };
  68411. return SIMDVector3;
  68412. }());
  68413. var SIMDMatrix = /** @class */ (function () {
  68414. function SIMDMatrix() {
  68415. }
  68416. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68417. var tm = this.m;
  68418. var om = other.m;
  68419. var m0 = SIMD.Float32x4.load(om, 0);
  68420. var m1 = SIMD.Float32x4.load(om, 4);
  68421. var m2 = SIMD.Float32x4.load(om, 8);
  68422. var m3 = SIMD.Float32x4.load(om, 12);
  68423. for (var i = 0; i < 16; i += 4) {
  68424. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  68425. }
  68426. return this;
  68427. };
  68428. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68429. var src = this.m;
  68430. var dest = other.m;
  68431. // Load the 4 rows
  68432. var src0 = SIMD.Float32x4.load(src, 0);
  68433. var src1 = SIMD.Float32x4.load(src, 4);
  68434. var src2 = SIMD.Float32x4.load(src, 8);
  68435. var src3 = SIMD.Float32x4.load(src, 12);
  68436. // Transpose the source matrix. Sort of. Not a true transpose operation
  68437. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68438. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68439. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68440. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  68441. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  68442. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  68443. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  68444. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  68445. // This is a true transposition, but it will lead to an incorrect result
  68446. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  68447. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  68448. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68449. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68450. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  68451. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  68452. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68453. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68454. // ----
  68455. tmp1 = SIMD.Float32x4.mul(row2, row3);
  68456. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68457. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  68458. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  68459. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68460. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  68461. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  68462. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  68463. // ----
  68464. tmp1 = SIMD.Float32x4.mul(row1, row2);
  68465. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68466. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  68467. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  68468. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68469. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  68470. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  68471. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  68472. // ----
  68473. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  68474. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68475. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  68476. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  68477. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  68478. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68479. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  68480. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  68481. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  68482. // ----
  68483. tmp1 = SIMD.Float32x4.mul(row0, row1);
  68484. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68485. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68486. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  68487. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68488. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68489. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  68490. // ----
  68491. tmp1 = SIMD.Float32x4.mul(row0, row3);
  68492. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68493. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  68494. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  68495. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68496. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  68497. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  68498. // ----
  68499. tmp1 = SIMD.Float32x4.mul(row0, row2);
  68500. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68501. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  68502. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  68503. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68504. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  68505. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  68506. // Compute determinant
  68507. var det = SIMD.Float32x4.mul(row0, minor0);
  68508. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  68509. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  68510. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  68511. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  68512. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  68513. // These shuffles aren't necessary if the faulty transposition is done
  68514. // up at the top of this function.
  68515. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  68516. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  68517. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  68518. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  68519. // Compute final values by multiplying with 1/det
  68520. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  68521. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  68522. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  68523. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  68524. return this;
  68525. };
  68526. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  68527. var out = result.m;
  68528. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  68529. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  68530. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  68531. // cc.kmVec3Subtract(f, pCenter, pEye);
  68532. var f = SIMD.Float32x4.sub(center, eye);
  68533. // cc.kmVec3Normalize(f, f);
  68534. var tmp = SIMD.Float32x4.mul(f, f);
  68535. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68536. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68537. // cc.kmVec3Assign(up, pUp);
  68538. // cc.kmVec3Normalize(up, up);
  68539. tmp = SIMD.Float32x4.mul(up, up);
  68540. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68541. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68542. // cc.kmVec3Cross(s, f, up);
  68543. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  68544. // cc.kmVec3Normalize(s, s);
  68545. tmp = SIMD.Float32x4.mul(s, s);
  68546. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68547. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68548. // cc.kmVec3Cross(u, s, f);
  68549. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  68550. // cc.kmVec3Normalize(s, s);
  68551. tmp = SIMD.Float32x4.mul(s, s);
  68552. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68553. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68554. var zero = SIMD.Float32x4.splat(0.0);
  68555. s = SIMD.Float32x4.neg(s);
  68556. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  68557. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  68558. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  68559. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  68560. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  68561. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  68562. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  68563. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68564. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  68565. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68566. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  68567. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68568. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  68569. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68570. };
  68571. return SIMDMatrix;
  68572. }());
  68573. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  68574. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  68575. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  68576. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  68577. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  68578. var SIMDHelper = /** @class */ (function () {
  68579. function SIMDHelper() {
  68580. }
  68581. Object.defineProperty(SIMDHelper, "IsEnabled", {
  68582. get: function () {
  68583. return SIMDHelper._isEnabled;
  68584. },
  68585. enumerable: true,
  68586. configurable: true
  68587. });
  68588. SIMDHelper.DisableSIMD = function () {
  68589. // Replace functions
  68590. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  68591. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  68592. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  68593. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  68594. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  68595. SIMDHelper._isEnabled = false;
  68596. };
  68597. SIMDHelper.EnableSIMD = function () {
  68598. if (self.SIMD === undefined) {
  68599. return;
  68600. }
  68601. // check if polyfills needed
  68602. if (!self.Math.fround) {
  68603. self.Math.fround = (function (array) { return function (x) {
  68604. return array[0] = x, array[0];
  68605. }; })(new Float32Array(1));
  68606. }
  68607. if (!self.Math.imul) {
  68608. self.Math.imul = function (a, b) {
  68609. var ah = (a >>> 16) & 0xffff;
  68610. var al = a & 0xffff;
  68611. var bh = (b >>> 16) & 0xffff;
  68612. var bl = b & 0xffff;
  68613. // the shift by 0 fixes the sign on the high part
  68614. // the final |0 converts the unsigned value into a signed value
  68615. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  68616. };
  68617. }
  68618. // Replace functions
  68619. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  68620. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  68621. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  68622. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  68623. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  68624. SIMDHelper._isEnabled = true;
  68625. };
  68626. SIMDHelper._isEnabled = false;
  68627. return SIMDHelper;
  68628. }());
  68629. BABYLON.SIMDHelper = SIMDHelper;
  68630. })(BABYLON || (BABYLON = {}));
  68631. //# sourceMappingURL=babylon.math.SIMD.js.map
  68632. var BABYLON;
  68633. (function (BABYLON) {
  68634. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  68635. __extends(VRDistortionCorrectionPostProcess, _super);
  68636. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  68637. var _this = _super.call(this, name, "vrDistortionCorrection", [
  68638. 'LensCenter',
  68639. 'Scale',
  68640. 'ScaleIn',
  68641. 'HmdWarpParam'
  68642. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  68643. _this._isRightEye = isRightEye;
  68644. _this._distortionFactors = vrMetrics.distortionK;
  68645. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  68646. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  68647. _this.adaptScaleToCurrentViewport = true;
  68648. _this.onSizeChangedObservable.add(function () {
  68649. _this.aspectRatio = _this.width * .5 / _this.height;
  68650. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  68651. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  68652. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  68653. });
  68654. _this.onApplyObservable.add(function (effect) {
  68655. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  68656. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  68657. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  68658. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  68659. });
  68660. return _this;
  68661. }
  68662. return VRDistortionCorrectionPostProcess;
  68663. }(BABYLON.PostProcess));
  68664. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  68665. })(BABYLON || (BABYLON = {}));
  68666. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  68667. var BABYLON;
  68668. (function (BABYLON) {
  68669. var AnaglyphPostProcess = /** @class */ (function (_super) {
  68670. __extends(AnaglyphPostProcess, _super);
  68671. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  68672. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  68673. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68674. _this.onApplyObservable.add(function (effect) {
  68675. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  68676. });
  68677. return _this;
  68678. }
  68679. return AnaglyphPostProcess;
  68680. }(BABYLON.PostProcess));
  68681. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  68682. })(BABYLON || (BABYLON = {}));
  68683. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  68684. var BABYLON;
  68685. (function (BABYLON) {
  68686. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  68687. __extends(StereoscopicInterlacePostProcess, _super);
  68688. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  68689. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  68690. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68691. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68692. _this.onSizeChangedObservable.add(function () {
  68693. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68694. });
  68695. _this.onApplyObservable.add(function (effect) {
  68696. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  68697. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  68698. });
  68699. return _this;
  68700. }
  68701. return StereoscopicInterlacePostProcess;
  68702. }(BABYLON.PostProcess));
  68703. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  68704. })(BABYLON || (BABYLON = {}));
  68705. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  68706. var BABYLON;
  68707. (function (BABYLON) {
  68708. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  68709. function FreeCameraDeviceOrientationInput() {
  68710. var _this = this;
  68711. this._screenOrientationAngle = 0;
  68712. this._screenQuaternion = new BABYLON.Quaternion();
  68713. this._alpha = 0;
  68714. this._beta = 0;
  68715. this._gamma = 0;
  68716. this._orientationChanged = function () {
  68717. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  68718. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  68719. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  68720. };
  68721. this._deviceOrientation = function (evt) {
  68722. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  68723. _this._beta = evt.beta !== null ? evt.beta : 0;
  68724. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  68725. };
  68726. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  68727. this._orientationChanged();
  68728. }
  68729. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  68730. get: function () {
  68731. return this._camera;
  68732. },
  68733. set: function (camera) {
  68734. this._camera = camera;
  68735. if (this._camera != null && !this._camera.rotationQuaternion) {
  68736. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  68737. }
  68738. },
  68739. enumerable: true,
  68740. configurable: true
  68741. });
  68742. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68743. window.addEventListener("orientationchange", this._orientationChanged);
  68744. window.addEventListener("deviceorientation", this._deviceOrientation);
  68745. //In certain cases, the attach control is called AFTER orientation was changed,
  68746. //So this is needed.
  68747. this._orientationChanged();
  68748. };
  68749. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  68750. window.removeEventListener("orientationchange", this._orientationChanged);
  68751. window.removeEventListener("deviceorientation", this._deviceOrientation);
  68752. };
  68753. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  68754. //if no device orientation provided, don't update the rotation.
  68755. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  68756. if (!this._alpha)
  68757. return;
  68758. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  68759. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  68760. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  68761. //Mirror on XY Plane
  68762. this._camera.rotationQuaternion.z *= -1;
  68763. this._camera.rotationQuaternion.w *= -1;
  68764. };
  68765. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  68766. return "FreeCameraDeviceOrientationInput";
  68767. };
  68768. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  68769. return "deviceOrientation";
  68770. };
  68771. return FreeCameraDeviceOrientationInput;
  68772. }());
  68773. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  68774. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  68775. })(BABYLON || (BABYLON = {}));
  68776. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  68777. var BABYLON;
  68778. (function (BABYLON) {
  68779. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  68780. function ArcRotateCameraVRDeviceOrientationInput() {
  68781. this.alphaCorrection = 1;
  68782. this.betaCorrection = 1;
  68783. this.gammaCorrection = 1;
  68784. this._alpha = 0;
  68785. this._beta = 0;
  68786. this._gamma = 0;
  68787. this._dirty = false;
  68788. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  68789. }
  68790. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68791. this.camera.attachControl(element, noPreventDefault);
  68792. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  68793. };
  68794. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  68795. if (evt.alpha !== null) {
  68796. this._alpha = +evt.alpha | 0;
  68797. }
  68798. if (evt.beta !== null) {
  68799. this._beta = +evt.beta | 0;
  68800. }
  68801. if (evt.gamma !== null) {
  68802. this._gamma = +evt.gamma | 0;
  68803. }
  68804. this._dirty = true;
  68805. };
  68806. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  68807. if (this._dirty) {
  68808. this._dirty = false;
  68809. if (this._gamma < 0) {
  68810. this._gamma = 180 + this._gamma;
  68811. }
  68812. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  68813. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  68814. }
  68815. };
  68816. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  68817. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  68818. };
  68819. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  68820. return "ArcRotateCameraVRDeviceOrientationInput";
  68821. };
  68822. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  68823. return "VRDeviceOrientation";
  68824. };
  68825. return ArcRotateCameraVRDeviceOrientationInput;
  68826. }());
  68827. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  68828. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  68829. })(BABYLON || (BABYLON = {}));
  68830. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  68831. var BABYLON;
  68832. (function (BABYLON) {
  68833. var VRCameraMetrics = /** @class */ (function () {
  68834. function VRCameraMetrics() {
  68835. this.compensateDistortion = true;
  68836. }
  68837. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  68838. get: function () {
  68839. return this.hResolution / (2 * this.vResolution);
  68840. },
  68841. enumerable: true,
  68842. configurable: true
  68843. });
  68844. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  68845. get: function () {
  68846. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  68847. },
  68848. enumerable: true,
  68849. configurable: true
  68850. });
  68851. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  68852. get: function () {
  68853. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  68854. var h = (4 * meters) / this.hScreenSize;
  68855. return BABYLON.Matrix.Translation(h, 0, 0);
  68856. },
  68857. enumerable: true,
  68858. configurable: true
  68859. });
  68860. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  68861. get: function () {
  68862. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  68863. var h = (4 * meters) / this.hScreenSize;
  68864. return BABYLON.Matrix.Translation(-h, 0, 0);
  68865. },
  68866. enumerable: true,
  68867. configurable: true
  68868. });
  68869. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  68870. get: function () {
  68871. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  68872. },
  68873. enumerable: true,
  68874. configurable: true
  68875. });
  68876. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  68877. get: function () {
  68878. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  68879. },
  68880. enumerable: true,
  68881. configurable: true
  68882. });
  68883. VRCameraMetrics.GetDefault = function () {
  68884. var result = new VRCameraMetrics();
  68885. result.hResolution = 1280;
  68886. result.vResolution = 800;
  68887. result.hScreenSize = 0.149759993;
  68888. result.vScreenSize = 0.0935999975;
  68889. result.vScreenCenter = 0.0467999987;
  68890. result.eyeToScreenDistance = 0.0410000011;
  68891. result.lensSeparationDistance = 0.0635000020;
  68892. result.interpupillaryDistance = 0.0640000030;
  68893. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  68894. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  68895. result.postProcessScaleFactor = 1.714605507808412;
  68896. result.lensCenterOffset = 0.151976421;
  68897. return result;
  68898. };
  68899. return VRCameraMetrics;
  68900. }());
  68901. BABYLON.VRCameraMetrics = VRCameraMetrics;
  68902. })(BABYLON || (BABYLON = {}));
  68903. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  68904. var BABYLON;
  68905. (function (BABYLON) {
  68906. var WebVRFreeCamera = /** @class */ (function (_super) {
  68907. __extends(WebVRFreeCamera, _super);
  68908. function WebVRFreeCamera(name, position, scene, webVROptions) {
  68909. if (webVROptions === void 0) { webVROptions = {}; }
  68910. var _this = _super.call(this, name, position, scene) || this;
  68911. _this.webVROptions = webVROptions;
  68912. _this._vrDevice = null;
  68913. _this.rawPose = null;
  68914. _this._specsVersion = "1.1";
  68915. _this._attached = false;
  68916. _this._descendants = [];
  68917. _this.devicePosition = BABYLON.Vector3.Zero();
  68918. _this.deviceScaleFactor = 1;
  68919. _this.controllers = [];
  68920. _this.onControllersAttachedObservable = new BABYLON.Observable();
  68921. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  68922. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  68923. _this.minZ = 0.1;
  68924. //legacy support - the compensation boolean was removed.
  68925. if (arguments.length === 5) {
  68926. _this.webVROptions = arguments[4];
  68927. }
  68928. // default webVR options
  68929. if (_this.webVROptions.trackPosition == undefined) {
  68930. _this.webVROptions.trackPosition = true;
  68931. }
  68932. if (_this.webVROptions.controllerMeshes == undefined) {
  68933. _this.webVROptions.controllerMeshes = true;
  68934. }
  68935. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  68936. _this.webVROptions.defaultLightingOnControllers = true;
  68937. }
  68938. _this.rotationQuaternion = new BABYLON.Quaternion();
  68939. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  68940. if (_this.webVROptions && _this.webVROptions.positionScale) {
  68941. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  68942. }
  68943. //enable VR
  68944. var engine = _this.getEngine();
  68945. _this._onVREnabled = function (success) { if (success) {
  68946. _this.initControllers();
  68947. } };
  68948. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  68949. engine.initWebVR().add(function (event) {
  68950. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  68951. return;
  68952. }
  68953. _this._vrDevice = event.vrDisplay;
  68954. //reset the rig parameters.
  68955. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  68956. if (_this._attached) {
  68957. _this.getEngine().enableVR();
  68958. }
  68959. });
  68960. if (typeof (VRFrameData) !== "undefined")
  68961. _this._frameData = new VRFrameData();
  68962. /**
  68963. * The idea behind the following lines:
  68964. * objects that have the camera as parent should actually have the rig cameras as a parent.
  68965. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  68966. * the second will not show it correctly.
  68967. *
  68968. * To solve this - each object that has the camera as parent will be added to a protected array.
  68969. * When the rig camera renders, it will take this array and set all of those to be its children.
  68970. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  68971. * Amazing!
  68972. */
  68973. scene.onBeforeCameraRenderObservable.add(function (camera) {
  68974. if (camera.parent === _this && _this.rigParenting) {
  68975. _this._descendants = _this.getDescendants(true, function (n) {
  68976. // don't take the cameras or the controllers!
  68977. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  68978. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  68979. return !isController && !isRigCamera;
  68980. });
  68981. _this._descendants.forEach(function (node) {
  68982. node.parent = camera;
  68983. });
  68984. }
  68985. });
  68986. scene.onAfterCameraRenderObservable.add(function (camera) {
  68987. if (camera.parent === _this && _this.rigParenting) {
  68988. _this._descendants.forEach(function (node) {
  68989. node.parent = _this;
  68990. });
  68991. }
  68992. });
  68993. return _this;
  68994. }
  68995. WebVRFreeCamera.prototype.dispose = function () {
  68996. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  68997. _super.prototype.dispose.call(this);
  68998. };
  68999. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69000. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69001. var gp = _a[_i];
  69002. if (gp.hand === name) {
  69003. return gp;
  69004. }
  69005. }
  69006. return null;
  69007. };
  69008. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69009. get: function () {
  69010. if (!this._leftController) {
  69011. this._leftController = this.getControllerByName("left");
  69012. }
  69013. return this._leftController;
  69014. },
  69015. enumerable: true,
  69016. configurable: true
  69017. });
  69018. ;
  69019. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69020. get: function () {
  69021. if (!this._rightController) {
  69022. this._rightController = this.getControllerByName("right");
  69023. }
  69024. return this._rightController;
  69025. },
  69026. enumerable: true,
  69027. configurable: true
  69028. });
  69029. ;
  69030. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69031. if (length === void 0) { length = 100; }
  69032. if (this.leftCamera) {
  69033. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69034. }
  69035. else {
  69036. return _super.prototype.getForwardRay.call(this, length);
  69037. }
  69038. };
  69039. WebVRFreeCamera.prototype._checkInputs = function () {
  69040. if (this._vrDevice && this._vrDevice.isPresenting) {
  69041. this._vrDevice.getFrameData(this._frameData);
  69042. this.updateFromDevice(this._frameData.pose);
  69043. }
  69044. _super.prototype._checkInputs.call(this);
  69045. };
  69046. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69047. if (poseData && poseData.orientation) {
  69048. this.rawPose = poseData;
  69049. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69050. if (this.getScene().useRightHandedSystem) {
  69051. this.deviceRotationQuaternion.z *= -1;
  69052. this.deviceRotationQuaternion.w *= -1;
  69053. }
  69054. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69055. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69056. if (this.getScene().useRightHandedSystem) {
  69057. this.devicePosition.z *= -1;
  69058. }
  69059. }
  69060. }
  69061. };
  69062. /**
  69063. * WebVR's attach control will start broadcasting frames to the device.
  69064. * Note that in certain browsers (chrome for example) this function must be called
  69065. * within a user-interaction callback. Example:
  69066. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69067. *
  69068. * @param {HTMLElement} element
  69069. * @param {boolean} [noPreventDefault]
  69070. *
  69071. * @memberOf WebVRFreeCamera
  69072. */
  69073. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69074. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69075. this._attached = true;
  69076. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69077. if (this._vrDevice) {
  69078. this.getEngine().enableVR();
  69079. }
  69080. };
  69081. WebVRFreeCamera.prototype.detachControl = function (element) {
  69082. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69083. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69084. _super.prototype.detachControl.call(this, element);
  69085. this._attached = false;
  69086. this.getEngine().disableVR();
  69087. };
  69088. WebVRFreeCamera.prototype.getClassName = function () {
  69089. return "WebVRFreeCamera";
  69090. };
  69091. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69092. //uses the vrDisplay's "resetPose()".
  69093. //pitch and roll won't be affected.
  69094. this._vrDevice.resetPose();
  69095. };
  69096. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69097. var camLeft = this._rigCameras[0];
  69098. var camRight = this._rigCameras[1];
  69099. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69100. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69101. camLeft.position.copyFrom(this.devicePosition);
  69102. camRight.position.copyFrom(this.devicePosition);
  69103. };
  69104. /**
  69105. * This function is called by the two RIG cameras.
  69106. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69107. */
  69108. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69109. var _this = this;
  69110. //WebVR 1.1
  69111. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69112. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69113. if (!this.getScene().useRightHandedSystem) {
  69114. [2, 6, 8, 9, 14].forEach(function (num) {
  69115. _this._webvrViewMatrix.m[num] *= -1;
  69116. });
  69117. }
  69118. // update the camera rotation matrix
  69119. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69120. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69121. // Computing target and final matrix
  69122. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69123. var parentCamera = this._cameraRigParams["parentCamera"];
  69124. // should the view matrix be updated with scale and position offset?
  69125. if (parentCamera.deviceScaleFactor !== 1) {
  69126. this._webvrViewMatrix.invert();
  69127. // scale the position, if set
  69128. if (parentCamera.deviceScaleFactor) {
  69129. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69130. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69131. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69132. }
  69133. this._webvrViewMatrix.invert();
  69134. }
  69135. return this._webvrViewMatrix;
  69136. };
  69137. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69138. var _this = this;
  69139. var parentCamera = this.parent;
  69140. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69141. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69142. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69143. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69144. //babylon compatible matrix
  69145. if (!this.getScene().useRightHandedSystem) {
  69146. [8, 9, 10, 11].forEach(function (num) {
  69147. _this._projectionMatrix.m[num] *= -1;
  69148. });
  69149. }
  69150. return this._projectionMatrix;
  69151. };
  69152. WebVRFreeCamera.prototype.initControllers = function () {
  69153. var _this = this;
  69154. this.controllers = [];
  69155. var manager = this.getScene().gamepadManager;
  69156. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69157. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69158. var webVrController = gamepad;
  69159. if (webVrController.defaultModel) {
  69160. webVrController.defaultModel.setEnabled(false);
  69161. }
  69162. }
  69163. });
  69164. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69165. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69166. var webVrController_1 = gamepad;
  69167. if (_this.webVROptions.controllerMeshes) {
  69168. if (webVrController_1.defaultModel) {
  69169. webVrController_1.defaultModel.setEnabled(true);
  69170. }
  69171. else {
  69172. // Load the meshes
  69173. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69174. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69175. if (_this.webVROptions.defaultLightingOnControllers) {
  69176. if (!_this._lightOnControllers) {
  69177. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69178. }
  69179. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69180. var children = mesh.getChildren();
  69181. if (children.length !== 0) {
  69182. children.forEach(function (mesh) {
  69183. light.includedOnlyMeshes.push(mesh);
  69184. activateLightOnSubMeshes_1(mesh, light);
  69185. });
  69186. }
  69187. };
  69188. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69189. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69190. }
  69191. });
  69192. }
  69193. }
  69194. webVrController_1.attachToPoseControlledCamera(_this);
  69195. // since this is async - sanity check. Is the controller already stored?
  69196. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69197. //add to the controllers array
  69198. _this.controllers.push(webVrController_1);
  69199. //did we find enough controllers? Great! let the developer know.
  69200. if (_this.controllers.length >= 2) {
  69201. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69202. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69203. // So we're overriding setting left & right manually to be sure
  69204. var firstViveWandDetected = false;
  69205. for (var i = 0; i < _this.controllers.length; i++) {
  69206. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69207. if (!firstViveWandDetected) {
  69208. firstViveWandDetected = true;
  69209. _this.controllers[i].hand = "left";
  69210. }
  69211. else {
  69212. _this.controllers[i].hand = "right";
  69213. }
  69214. }
  69215. }
  69216. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69217. }
  69218. }
  69219. }
  69220. });
  69221. };
  69222. return WebVRFreeCamera;
  69223. }(BABYLON.FreeCamera));
  69224. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69225. })(BABYLON || (BABYLON = {}));
  69226. //# sourceMappingURL=babylon.webVRCamera.js.map
  69227. /// <reference path="babylon.freeCamera.ts" />
  69228. var BABYLON;
  69229. (function (BABYLON) {
  69230. // We're mainly based on the logic defined into the FreeCamera code
  69231. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69232. __extends(DeviceOrientationCamera, _super);
  69233. function DeviceOrientationCamera(name, position, scene) {
  69234. var _this = _super.call(this, name, position, scene) || this;
  69235. _this._quaternionCache = new BABYLON.Quaternion();
  69236. _this.inputs.addDeviceOrientation();
  69237. return _this;
  69238. }
  69239. DeviceOrientationCamera.prototype.getClassName = function () {
  69240. return "DeviceOrientationCamera";
  69241. };
  69242. DeviceOrientationCamera.prototype._checkInputs = function () {
  69243. _super.prototype._checkInputs.call(this);
  69244. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69245. if (this._initialQuaternion) {
  69246. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69247. }
  69248. };
  69249. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69250. var _this = this;
  69251. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69252. //can only work if this camera has a rotation quaternion already.
  69253. if (!this.rotationQuaternion)
  69254. return;
  69255. if (!this._initialQuaternion) {
  69256. this._initialQuaternion = new BABYLON.Quaternion();
  69257. }
  69258. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69259. ['x', 'y', 'z'].forEach(function (axisName) {
  69260. if (!axis[axisName]) {
  69261. _this._initialQuaternion[axisName] = 0;
  69262. }
  69263. else {
  69264. _this._initialQuaternion[axisName] *= -1;
  69265. }
  69266. });
  69267. this._initialQuaternion.normalize();
  69268. //force rotation update
  69269. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69270. };
  69271. return DeviceOrientationCamera;
  69272. }(BABYLON.FreeCamera));
  69273. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69274. })(BABYLON || (BABYLON = {}));
  69275. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69276. var BABYLON;
  69277. (function (BABYLON) {
  69278. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69279. __extends(VRDeviceOrientationFreeCamera, _super);
  69280. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69281. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69282. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69283. var _this = _super.call(this, name, position, scene) || this;
  69284. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69285. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69286. return _this;
  69287. }
  69288. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69289. return "VRDeviceOrientationFreeCamera";
  69290. };
  69291. return VRDeviceOrientationFreeCamera;
  69292. }(BABYLON.DeviceOrientationCamera));
  69293. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69294. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69295. __extends(VRDeviceOrientationGamepadCamera, _super);
  69296. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69297. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69298. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69299. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69300. _this.inputs.addGamepad();
  69301. return _this;
  69302. }
  69303. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69304. return "VRDeviceOrientationGamepadCamera";
  69305. };
  69306. return VRDeviceOrientationGamepadCamera;
  69307. }(VRDeviceOrientationFreeCamera));
  69308. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69309. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69310. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69311. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69312. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69313. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69314. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69315. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69316. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69317. _this.inputs.addVRDeviceOrientation();
  69318. return _this;
  69319. }
  69320. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69321. return "VRDeviceOrientationArcRotateCamera";
  69322. };
  69323. return VRDeviceOrientationArcRotateCamera;
  69324. }(BABYLON.ArcRotateCamera));
  69325. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69326. })(BABYLON || (BABYLON = {}));
  69327. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69328. /// <reference path="babylon.freeCamera.ts" />
  69329. /// <reference path="babylon.arcRotateCamera.ts" />
  69330. /// <reference path="babylon.gamepadCamera.ts" />
  69331. /// <reference path="babylon.universalCamera.ts" />
  69332. var BABYLON;
  69333. (function (BABYLON) {
  69334. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69335. __extends(AnaglyphFreeCamera, _super);
  69336. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69337. var _this = _super.call(this, name, position, scene) || this;
  69338. _this.interaxialDistance = interaxialDistance;
  69339. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69340. return _this;
  69341. }
  69342. AnaglyphFreeCamera.prototype.getClassName = function () {
  69343. return "AnaglyphFreeCamera";
  69344. };
  69345. return AnaglyphFreeCamera;
  69346. }(BABYLON.FreeCamera));
  69347. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69348. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69349. __extends(AnaglyphArcRotateCamera, _super);
  69350. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69351. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69352. _this.interaxialDistance = interaxialDistance;
  69353. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69354. return _this;
  69355. }
  69356. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69357. return "AnaglyphArcRotateCamera";
  69358. };
  69359. return AnaglyphArcRotateCamera;
  69360. }(BABYLON.ArcRotateCamera));
  69361. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69362. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69363. __extends(AnaglyphGamepadCamera, _super);
  69364. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69365. var _this = _super.call(this, name, position, scene) || this;
  69366. _this.interaxialDistance = interaxialDistance;
  69367. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69368. return _this;
  69369. }
  69370. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69371. return "AnaglyphGamepadCamera";
  69372. };
  69373. return AnaglyphGamepadCamera;
  69374. }(BABYLON.GamepadCamera));
  69375. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69376. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69377. __extends(AnaglyphUniversalCamera, _super);
  69378. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69379. var _this = _super.call(this, name, position, scene) || this;
  69380. _this.interaxialDistance = interaxialDistance;
  69381. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69382. return _this;
  69383. }
  69384. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69385. return "AnaglyphUniversalCamera";
  69386. };
  69387. return AnaglyphUniversalCamera;
  69388. }(BABYLON.UniversalCamera));
  69389. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69390. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69391. __extends(StereoscopicFreeCamera, _super);
  69392. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69393. var _this = _super.call(this, name, position, scene) || this;
  69394. _this.interaxialDistance = interaxialDistance;
  69395. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69396. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69397. return _this;
  69398. }
  69399. StereoscopicFreeCamera.prototype.getClassName = function () {
  69400. return "StereoscopicFreeCamera";
  69401. };
  69402. return StereoscopicFreeCamera;
  69403. }(BABYLON.FreeCamera));
  69404. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69405. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69406. __extends(StereoscopicArcRotateCamera, _super);
  69407. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69408. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69409. _this.interaxialDistance = interaxialDistance;
  69410. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69411. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69412. return _this;
  69413. }
  69414. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69415. return "StereoscopicArcRotateCamera";
  69416. };
  69417. return StereoscopicArcRotateCamera;
  69418. }(BABYLON.ArcRotateCamera));
  69419. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69420. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69421. __extends(StereoscopicGamepadCamera, _super);
  69422. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69423. var _this = _super.call(this, name, position, scene) || this;
  69424. _this.interaxialDistance = interaxialDistance;
  69425. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69426. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69427. return _this;
  69428. }
  69429. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69430. return "StereoscopicGamepadCamera";
  69431. };
  69432. return StereoscopicGamepadCamera;
  69433. }(BABYLON.GamepadCamera));
  69434. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69435. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69436. __extends(StereoscopicUniversalCamera, _super);
  69437. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69438. var _this = _super.call(this, name, position, scene) || this;
  69439. _this.interaxialDistance = interaxialDistance;
  69440. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69441. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69442. return _this;
  69443. }
  69444. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69445. return "StereoscopicUniversalCamera";
  69446. };
  69447. return StereoscopicUniversalCamera;
  69448. }(BABYLON.UniversalCamera));
  69449. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  69450. })(BABYLON || (BABYLON = {}));
  69451. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  69452. var BABYLON;
  69453. (function (BABYLON) {
  69454. var VRExperienceHelper = /** @class */ (function () {
  69455. function VRExperienceHelper(scene, webVROptions) {
  69456. if (webVROptions === void 0) { webVROptions = {}; }
  69457. var _this = this;
  69458. this.webVROptions = webVROptions;
  69459. // Can the system support WebVR, even if a headset isn't plugged in?
  69460. this._webVRsupported = false;
  69461. // If WebVR is supported, is a headset plugged in and are we ready to present?
  69462. this._webVRready = false;
  69463. // Are we waiting for the requestPresent callback to complete?
  69464. this._webVRrequesting = false;
  69465. // Are we presenting to the headset right now?
  69466. this._webVRpresenting = false;
  69467. // Are we presenting in the fullscreen fallback?
  69468. this._fullscreenVRpresenting = false;
  69469. this._scene = scene;
  69470. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  69471. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  69472. }
  69473. else {
  69474. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  69475. if (scene.activeCamera.rotation) {
  69476. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  69477. }
  69478. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  69479. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  69480. }
  69481. this._scene.activeCamera = this._deviceOrientationCamera;
  69482. this._position = this._scene.activeCamera.position;
  69483. this._canvas = scene.getEngine().getRenderingCanvas();
  69484. if (this._canvas) {
  69485. this._scene.activeCamera.attachControl(this._canvas);
  69486. }
  69487. this._btnVR = document.createElement("BUTTON");
  69488. this._btnVR.className = "babylonVRicon";
  69489. this._btnVR.id = "babylonVRiconbtn";
  69490. this._btnVR.title = "Click to switch to VR";
  69491. 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) }";
  69492. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  69493. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  69494. // css += ".babylonVRicon.vrdisplaysupported { }";
  69495. // css += ".babylonVRicon.vrdisplayready { }";
  69496. // css += ".babylonVRicon.vrdisplayrequesting { }";
  69497. var style = document.createElement('style');
  69498. style.appendChild(document.createTextNode(css));
  69499. document.getElementsByTagName('head')[0].appendChild(style);
  69500. if (this._canvas) {
  69501. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69502. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69503. this._btnVR.addEventListener("click", function () {
  69504. _this.enterVR();
  69505. });
  69506. window.addEventListener("resize", function () {
  69507. if (_this._canvas) {
  69508. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  69509. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  69510. }
  69511. if (_this._fullscreenVRpresenting && _this._webVRready) {
  69512. _this.exitVR();
  69513. }
  69514. });
  69515. }
  69516. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69517. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69518. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69519. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69520. document.body.appendChild(this._btnVR);
  69521. // Exiting VR mode using 'ESC' key on desktop
  69522. this._onKeyDown = function (event) {
  69523. if (event.keyCode === 27 && _this.isInVRMode()) {
  69524. _this.exitVR();
  69525. }
  69526. };
  69527. document.addEventListener("keydown", this._onKeyDown);
  69528. // Exiting VR mode double tapping the touch screen
  69529. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  69530. if (_this.isInVRMode()) {
  69531. _this.exitVR();
  69532. if (_this._fullscreenVRpresenting) {
  69533. _this._scene.getEngine().switchFullscreen(true);
  69534. }
  69535. }
  69536. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  69537. // Listen for WebVR display changes
  69538. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  69539. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  69540. this._onVRRequestPresentStart = function () {
  69541. _this._webVRrequesting = true;
  69542. _this.updateButtonVisibility();
  69543. };
  69544. this._onVRRequestPresentComplete = function (success) {
  69545. _this._webVRrequesting = false;
  69546. _this.updateButtonVisibility();
  69547. };
  69548. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  69549. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  69550. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  69551. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69552. // Create the cameras
  69553. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  69554. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  69555. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  69556. this.updateButtonVisibility();
  69557. }
  69558. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  69559. if (this.onControllerMeshLoaded) {
  69560. this.onControllerMeshLoaded(webVRController);
  69561. }
  69562. };
  69563. VRExperienceHelper.prototype._onFullscreenChange = function () {
  69564. if (document.fullscreen !== undefined) {
  69565. this._fullscreenVRpresenting = document.fullscreen;
  69566. }
  69567. else if (document.mozFullScreen !== undefined) {
  69568. this._fullscreenVRpresenting = document.mozFullScreen;
  69569. }
  69570. else if (document.webkitIsFullScreen !== undefined) {
  69571. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  69572. }
  69573. else if (document.msIsFullScreen !== undefined) {
  69574. this._fullscreenVRpresenting = document.msIsFullScreen;
  69575. }
  69576. if (!this._fullscreenVRpresenting && this._canvas) {
  69577. this.exitVR();
  69578. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69579. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69580. }
  69581. };
  69582. VRExperienceHelper.prototype.isInVRMode = function () {
  69583. return this._webVRpresenting || this._fullscreenVRpresenting;
  69584. };
  69585. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  69586. var vrDisplay = this._scene.getEngine().getVRDevice();
  69587. if (vrDisplay) {
  69588. var wasPresenting = this._webVRpresenting;
  69589. // A VR display is connected
  69590. this._webVRpresenting = vrDisplay.isPresenting;
  69591. if (wasPresenting && !this._webVRpresenting)
  69592. this.exitVR();
  69593. }
  69594. else {
  69595. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  69596. }
  69597. this.updateButtonVisibility();
  69598. };
  69599. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  69600. this._webVRsupported = eventArgs.vrSupported;
  69601. this._webVRready = !!eventArgs.vrDisplay;
  69602. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  69603. this.updateButtonVisibility();
  69604. };
  69605. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  69606. if (!this._btnVR) {
  69607. return;
  69608. }
  69609. this._btnVR.className = "babylonVRicon";
  69610. if (this.isInVRMode()) {
  69611. this._btnVR.className += " vrdisplaypresenting";
  69612. }
  69613. else {
  69614. if (this._webVRready)
  69615. this._btnVR.className += " vrdisplayready";
  69616. if (this._webVRsupported)
  69617. this._btnVR.className += " vrdisplaysupported";
  69618. if (this._webVRrequesting)
  69619. this._btnVR.className += " vrdisplayrequesting";
  69620. }
  69621. };
  69622. /**
  69623. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  69624. * Otherwise, will use the fullscreen API.
  69625. */
  69626. VRExperienceHelper.prototype.enterVR = function () {
  69627. if (this.onEnteringVR) {
  69628. this.onEnteringVR();
  69629. }
  69630. if (this._webVRrequesting)
  69631. return;
  69632. // If WebVR is supported and a headset is connected
  69633. if (this._webVRready) {
  69634. if (!this._webVRpresenting) {
  69635. this._webVRCamera.position = this._position;
  69636. this._scene.activeCamera = this._webVRCamera;
  69637. }
  69638. }
  69639. else {
  69640. this._vrDeviceOrientationCamera.position = this._position;
  69641. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  69642. this._scene.getEngine().switchFullscreen(true);
  69643. this.updateButtonVisibility();
  69644. }
  69645. if (this._scene.activeCamera && this._canvas) {
  69646. this._scene.activeCamera.attachControl(this._canvas);
  69647. }
  69648. };
  69649. /**
  69650. * Attempt to exit VR, or fullscreen.
  69651. */
  69652. VRExperienceHelper.prototype.exitVR = function () {
  69653. if (this.onExitingVR) {
  69654. this.onExitingVR();
  69655. }
  69656. if (this._webVRpresenting) {
  69657. this._scene.getEngine().disableVR();
  69658. }
  69659. if (this._scene.activeCamera) {
  69660. this._position = this._scene.activeCamera.position;
  69661. }
  69662. this._deviceOrientationCamera.position = this._position;
  69663. this._scene.activeCamera = this._deviceOrientationCamera;
  69664. if (this._canvas) {
  69665. this._scene.activeCamera.attachControl(this._canvas);
  69666. }
  69667. this.updateButtonVisibility();
  69668. };
  69669. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  69670. get: function () {
  69671. return this._position;
  69672. },
  69673. set: function (value) {
  69674. this._position = value;
  69675. if (this._scene.activeCamera) {
  69676. this._scene.activeCamera.position = value;
  69677. }
  69678. },
  69679. enumerable: true,
  69680. configurable: true
  69681. });
  69682. VRExperienceHelper.prototype.dispose = function () {
  69683. if (this.isInVRMode()) {
  69684. this.exitVR();
  69685. }
  69686. this._deviceOrientationCamera.dispose();
  69687. if (this._webVRCamera) {
  69688. this._webVRCamera.dispose();
  69689. }
  69690. if (this._vrDeviceOrientationCamera) {
  69691. this._vrDeviceOrientationCamera.dispose();
  69692. }
  69693. document.body.removeChild(this._btnVR);
  69694. document.removeEventListener("keydown", this._onKeyDown);
  69695. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69696. };
  69697. VRExperienceHelper.prototype.getClassName = function () {
  69698. return "VRExperienceHelper";
  69699. };
  69700. return VRExperienceHelper;
  69701. }());
  69702. BABYLON.VRExperienceHelper = VRExperienceHelper;
  69703. })(BABYLON || (BABYLON = {}));
  69704. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  69705. // Mainly based on these 2 articles :
  69706. // 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
  69707. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  69708. var BABYLON;
  69709. (function (BABYLON) {
  69710. var JoystickAxis;
  69711. (function (JoystickAxis) {
  69712. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  69713. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  69714. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  69715. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  69716. var VirtualJoystick = /** @class */ (function () {
  69717. function VirtualJoystick(leftJoystick) {
  69718. var _this = this;
  69719. if (leftJoystick) {
  69720. this._leftJoystick = true;
  69721. }
  69722. else {
  69723. this._leftJoystick = false;
  69724. }
  69725. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  69726. VirtualJoystick._globalJoystickIndex++;
  69727. // By default left & right arrow keys are moving the X
  69728. // and up & down keys are moving the Y
  69729. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  69730. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  69731. this.reverseLeftRight = false;
  69732. this.reverseUpDown = false;
  69733. // collections of pointers
  69734. this._touches = new BABYLON.StringDictionary();
  69735. this.deltaPosition = BABYLON.Vector3.Zero();
  69736. this._joystickSensibility = 25;
  69737. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69738. this._rotationSpeed = 25;
  69739. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  69740. this._rotateOnAxisRelativeToMesh = false;
  69741. this._onResize = function (evt) {
  69742. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69743. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69744. if (VirtualJoystick.vjCanvas) {
  69745. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  69746. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  69747. }
  69748. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  69749. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  69750. };
  69751. // injecting a canvas element on top of the canvas 3D game
  69752. if (!VirtualJoystick.vjCanvas) {
  69753. window.addEventListener("resize", this._onResize, false);
  69754. VirtualJoystick.vjCanvas = document.createElement("canvas");
  69755. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69756. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69757. VirtualJoystick.vjCanvas.width = window.innerWidth;
  69758. VirtualJoystick.vjCanvas.height = window.innerHeight;
  69759. VirtualJoystick.vjCanvas.style.width = "100%";
  69760. VirtualJoystick.vjCanvas.style.height = "100%";
  69761. VirtualJoystick.vjCanvas.style.position = "absolute";
  69762. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  69763. VirtualJoystick.vjCanvas.style.top = "0px";
  69764. VirtualJoystick.vjCanvas.style.left = "0px";
  69765. VirtualJoystick.vjCanvas.style.zIndex = "5";
  69766. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  69767. // Support for jQuery PEP polyfill
  69768. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  69769. var context = VirtualJoystick.vjCanvas.getContext('2d');
  69770. if (!context) {
  69771. throw new Error("Unable to create canvas for virtual joystick");
  69772. }
  69773. VirtualJoystick.vjCanvasContext = context;
  69774. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  69775. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  69776. document.body.appendChild(VirtualJoystick.vjCanvas);
  69777. }
  69778. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  69779. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  69780. this.pressed = false;
  69781. // default joystick color
  69782. this._joystickColor = "cyan";
  69783. this._joystickPointerID = -1;
  69784. // current joystick position
  69785. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  69786. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  69787. // origin joystick position
  69788. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  69789. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  69790. this._onPointerDownHandlerRef = function (evt) {
  69791. _this._onPointerDown(evt);
  69792. };
  69793. this._onPointerMoveHandlerRef = function (evt) {
  69794. _this._onPointerMove(evt);
  69795. };
  69796. this._onPointerOutHandlerRef = function (evt) {
  69797. _this._onPointerUp(evt);
  69798. };
  69799. this._onPointerUpHandlerRef = function (evt) {
  69800. _this._onPointerUp(evt);
  69801. };
  69802. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  69803. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  69804. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  69805. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  69806. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  69807. evt.preventDefault(); // Disables system menu
  69808. }, false);
  69809. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  69810. }
  69811. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  69812. this._joystickSensibility = newJoystickSensibility;
  69813. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69814. };
  69815. VirtualJoystick.prototype._onPointerDown = function (e) {
  69816. var positionOnScreenCondition;
  69817. e.preventDefault();
  69818. if (this._leftJoystick === true) {
  69819. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  69820. }
  69821. else {
  69822. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  69823. }
  69824. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  69825. // First contact will be dedicated to the virtual joystick
  69826. this._joystickPointerID = e.pointerId;
  69827. this._joystickPointerStartPos.x = e.clientX;
  69828. this._joystickPointerStartPos.y = e.clientY;
  69829. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  69830. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  69831. this._deltaJoystickVector.x = 0;
  69832. this._deltaJoystickVector.y = 0;
  69833. this.pressed = true;
  69834. this._touches.add(e.pointerId.toString(), e);
  69835. }
  69836. else {
  69837. // You can only trigger the action buttons with a joystick declared
  69838. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  69839. this._action();
  69840. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  69841. }
  69842. }
  69843. };
  69844. VirtualJoystick.prototype._onPointerMove = function (e) {
  69845. // If the current pointer is the one associated to the joystick (first touch contact)
  69846. if (this._joystickPointerID == e.pointerId) {
  69847. this._joystickPointerPos.x = e.clientX;
  69848. this._joystickPointerPos.y = e.clientY;
  69849. this._deltaJoystickVector = this._joystickPointerPos.clone();
  69850. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  69851. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  69852. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  69853. switch (this._axisTargetedByLeftAndRight) {
  69854. case JoystickAxis.X:
  69855. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  69856. break;
  69857. case JoystickAxis.Y:
  69858. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  69859. break;
  69860. case JoystickAxis.Z:
  69861. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  69862. break;
  69863. }
  69864. var directionUpDown = this.reverseUpDown ? 1 : -1;
  69865. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  69866. switch (this._axisTargetedByUpAndDown) {
  69867. case JoystickAxis.X:
  69868. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  69869. break;
  69870. case JoystickAxis.Y:
  69871. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  69872. break;
  69873. case JoystickAxis.Z:
  69874. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  69875. break;
  69876. }
  69877. }
  69878. else {
  69879. var data = this._touches.get(e.pointerId.toString());
  69880. if (data) {
  69881. data.x = e.clientX;
  69882. data.y = e.clientY;
  69883. }
  69884. }
  69885. };
  69886. VirtualJoystick.prototype._onPointerUp = function (e) {
  69887. if (this._joystickPointerID == e.pointerId) {
  69888. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  69889. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  69890. this._joystickPointerID = -1;
  69891. this.pressed = false;
  69892. }
  69893. else {
  69894. var touch = this._touches.get(e.pointerId.toString());
  69895. if (touch) {
  69896. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  69897. }
  69898. }
  69899. this._deltaJoystickVector.x = 0;
  69900. this._deltaJoystickVector.y = 0;
  69901. this._touches.remove(e.pointerId.toString());
  69902. };
  69903. /**
  69904. * Change the color of the virtual joystick
  69905. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  69906. */
  69907. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  69908. this._joystickColor = newColor;
  69909. };
  69910. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  69911. this._action = action;
  69912. };
  69913. // Define which axis you'd like to control for left & right
  69914. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  69915. switch (axis) {
  69916. case JoystickAxis.X:
  69917. case JoystickAxis.Y:
  69918. case JoystickAxis.Z:
  69919. this._axisTargetedByLeftAndRight = axis;
  69920. break;
  69921. default:
  69922. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  69923. break;
  69924. }
  69925. };
  69926. // Define which axis you'd like to control for up & down
  69927. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  69928. switch (axis) {
  69929. case JoystickAxis.X:
  69930. case JoystickAxis.Y:
  69931. case JoystickAxis.Z:
  69932. this._axisTargetedByUpAndDown = axis;
  69933. break;
  69934. default:
  69935. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  69936. break;
  69937. }
  69938. };
  69939. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  69940. var _this = this;
  69941. if (this.pressed) {
  69942. this._touches.forEach(function (key, touch) {
  69943. if (touch.pointerId === _this._joystickPointerID) {
  69944. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  69945. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  69946. VirtualJoystick.vjCanvasContext.beginPath();
  69947. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  69948. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  69949. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  69950. VirtualJoystick.vjCanvasContext.stroke();
  69951. VirtualJoystick.vjCanvasContext.closePath();
  69952. VirtualJoystick.vjCanvasContext.beginPath();
  69953. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  69954. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  69955. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  69956. VirtualJoystick.vjCanvasContext.stroke();
  69957. VirtualJoystick.vjCanvasContext.closePath();
  69958. VirtualJoystick.vjCanvasContext.beginPath();
  69959. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  69960. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  69961. VirtualJoystick.vjCanvasContext.stroke();
  69962. VirtualJoystick.vjCanvasContext.closePath();
  69963. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  69964. }
  69965. else {
  69966. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  69967. VirtualJoystick.vjCanvasContext.beginPath();
  69968. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  69969. VirtualJoystick.vjCanvasContext.beginPath();
  69970. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  69971. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  69972. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  69973. VirtualJoystick.vjCanvasContext.stroke();
  69974. VirtualJoystick.vjCanvasContext.closePath();
  69975. touch.prevX = touch.x;
  69976. touch.prevY = touch.y;
  69977. }
  69978. ;
  69979. });
  69980. }
  69981. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  69982. };
  69983. VirtualJoystick.prototype.releaseCanvas = function () {
  69984. if (VirtualJoystick.vjCanvas) {
  69985. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  69986. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  69987. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  69988. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  69989. window.removeEventListener("resize", this._onResize);
  69990. document.body.removeChild(VirtualJoystick.vjCanvas);
  69991. VirtualJoystick.vjCanvas = null;
  69992. }
  69993. };
  69994. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  69995. VirtualJoystick._globalJoystickIndex = 0;
  69996. return VirtualJoystick;
  69997. }());
  69998. BABYLON.VirtualJoystick = VirtualJoystick;
  69999. })(BABYLON || (BABYLON = {}));
  70000. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70001. var BABYLON;
  70002. (function (BABYLON) {
  70003. // We're mainly based on the logic defined into the FreeCamera code
  70004. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70005. __extends(VirtualJoysticksCamera, _super);
  70006. function VirtualJoysticksCamera(name, position, scene) {
  70007. var _this = _super.call(this, name, position, scene) || this;
  70008. _this.inputs.addVirtualJoystick();
  70009. return _this;
  70010. }
  70011. VirtualJoysticksCamera.prototype.getClassName = function () {
  70012. return "VirtualJoysticksCamera";
  70013. };
  70014. return VirtualJoysticksCamera;
  70015. }(BABYLON.FreeCamera));
  70016. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70017. })(BABYLON || (BABYLON = {}));
  70018. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70019. var BABYLON;
  70020. (function (BABYLON) {
  70021. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70022. function FreeCameraVirtualJoystickInput() {
  70023. }
  70024. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70025. return this._leftjoystick;
  70026. };
  70027. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70028. return this._rightjoystick;
  70029. };
  70030. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70031. if (this._leftjoystick) {
  70032. var camera = this.camera;
  70033. var speed = camera._computeLocalCameraSpeed() * 50;
  70034. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70035. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70036. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70037. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70038. if (!this._leftjoystick.pressed) {
  70039. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70040. }
  70041. if (!this._rightjoystick.pressed) {
  70042. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70043. }
  70044. }
  70045. };
  70046. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70047. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70048. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70049. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70050. this._leftjoystick.setJoystickSensibility(0.15);
  70051. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70052. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70053. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70054. this._rightjoystick.reverseUpDown = true;
  70055. this._rightjoystick.setJoystickSensibility(0.05);
  70056. this._rightjoystick.setJoystickColor("yellow");
  70057. };
  70058. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70059. this._leftjoystick.releaseCanvas();
  70060. this._rightjoystick.releaseCanvas();
  70061. };
  70062. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70063. return "FreeCameraVirtualJoystickInput";
  70064. };
  70065. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70066. return "virtualJoystick";
  70067. };
  70068. return FreeCameraVirtualJoystickInput;
  70069. }());
  70070. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70071. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70072. })(BABYLON || (BABYLON = {}));
  70073. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70074. var BABYLON;
  70075. (function (BABYLON) {
  70076. var SimplificationSettings = /** @class */ (function () {
  70077. function SimplificationSettings(quality, distance, optimizeMesh) {
  70078. this.quality = quality;
  70079. this.distance = distance;
  70080. this.optimizeMesh = optimizeMesh;
  70081. }
  70082. return SimplificationSettings;
  70083. }());
  70084. BABYLON.SimplificationSettings = SimplificationSettings;
  70085. var SimplificationQueue = /** @class */ (function () {
  70086. function SimplificationQueue() {
  70087. this.running = false;
  70088. this._simplificationArray = [];
  70089. }
  70090. SimplificationQueue.prototype.addTask = function (task) {
  70091. this._simplificationArray.push(task);
  70092. };
  70093. SimplificationQueue.prototype.executeNext = function () {
  70094. var task = this._simplificationArray.pop();
  70095. if (task) {
  70096. this.running = true;
  70097. this.runSimplification(task);
  70098. }
  70099. else {
  70100. this.running = false;
  70101. }
  70102. };
  70103. SimplificationQueue.prototype.runSimplification = function (task) {
  70104. var _this = this;
  70105. if (task.parallelProcessing) {
  70106. //parallel simplifier
  70107. task.settings.forEach(function (setting) {
  70108. var simplifier = _this.getSimplifier(task);
  70109. simplifier.simplify(setting, function (newMesh) {
  70110. task.mesh.addLODLevel(setting.distance, newMesh);
  70111. newMesh.isVisible = true;
  70112. //check if it is the last
  70113. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70114. //all done, run the success callback.
  70115. task.successCallback();
  70116. }
  70117. _this.executeNext();
  70118. });
  70119. });
  70120. }
  70121. else {
  70122. //single simplifier.
  70123. var simplifier = this.getSimplifier(task);
  70124. var runDecimation = function (setting, callback) {
  70125. simplifier.simplify(setting, function (newMesh) {
  70126. task.mesh.addLODLevel(setting.distance, newMesh);
  70127. newMesh.isVisible = true;
  70128. //run the next quality level
  70129. callback();
  70130. });
  70131. };
  70132. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70133. runDecimation(task.settings[loop.index], function () {
  70134. loop.executeNext();
  70135. });
  70136. }, function () {
  70137. //execution ended, run the success callback.
  70138. if (task.successCallback) {
  70139. task.successCallback();
  70140. }
  70141. _this.executeNext();
  70142. });
  70143. }
  70144. };
  70145. SimplificationQueue.prototype.getSimplifier = function (task) {
  70146. switch (task.simplificationType) {
  70147. case SimplificationType.QUADRATIC:
  70148. default:
  70149. return new QuadraticErrorSimplification(task.mesh);
  70150. }
  70151. };
  70152. return SimplificationQueue;
  70153. }());
  70154. BABYLON.SimplificationQueue = SimplificationQueue;
  70155. /**
  70156. * The implemented types of simplification.
  70157. * At the moment only Quadratic Error Decimation is implemented.
  70158. */
  70159. var SimplificationType;
  70160. (function (SimplificationType) {
  70161. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70162. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70163. var DecimationTriangle = /** @class */ (function () {
  70164. function DecimationTriangle(vertices) {
  70165. this.vertices = vertices;
  70166. this.error = new Array(4);
  70167. this.deleted = false;
  70168. this.isDirty = false;
  70169. this.deletePending = false;
  70170. this.borderFactor = 0;
  70171. }
  70172. return DecimationTriangle;
  70173. }());
  70174. BABYLON.DecimationTriangle = DecimationTriangle;
  70175. var DecimationVertex = /** @class */ (function () {
  70176. function DecimationVertex(position, id) {
  70177. this.position = position;
  70178. this.id = id;
  70179. this.isBorder = true;
  70180. this.q = new QuadraticMatrix();
  70181. this.triangleCount = 0;
  70182. this.triangleStart = 0;
  70183. this.originalOffsets = [];
  70184. }
  70185. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70186. this.position.copyFrom(newPosition);
  70187. };
  70188. return DecimationVertex;
  70189. }());
  70190. BABYLON.DecimationVertex = DecimationVertex;
  70191. var QuadraticMatrix = /** @class */ (function () {
  70192. function QuadraticMatrix(data) {
  70193. this.data = new Array(10);
  70194. for (var i = 0; i < 10; ++i) {
  70195. if (data && data[i]) {
  70196. this.data[i] = data[i];
  70197. }
  70198. else {
  70199. this.data[i] = 0;
  70200. }
  70201. }
  70202. }
  70203. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70204. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70205. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70206. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70207. return det;
  70208. };
  70209. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70210. for (var i = 0; i < 10; ++i) {
  70211. this.data[i] += matrix.data[i];
  70212. }
  70213. };
  70214. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70215. for (var i = 0; i < 10; ++i) {
  70216. this.data[i] += data[i];
  70217. }
  70218. };
  70219. QuadraticMatrix.prototype.add = function (matrix) {
  70220. var m = new QuadraticMatrix();
  70221. for (var i = 0; i < 10; ++i) {
  70222. m.data[i] = this.data[i] + matrix.data[i];
  70223. }
  70224. return m;
  70225. };
  70226. QuadraticMatrix.FromData = function (a, b, c, d) {
  70227. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70228. };
  70229. //returning an array to avoid garbage collection
  70230. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70231. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70232. };
  70233. return QuadraticMatrix;
  70234. }());
  70235. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70236. var Reference = /** @class */ (function () {
  70237. function Reference(vertexId, triangleId) {
  70238. this.vertexId = vertexId;
  70239. this.triangleId = triangleId;
  70240. }
  70241. return Reference;
  70242. }());
  70243. BABYLON.Reference = Reference;
  70244. /**
  70245. * An implementation of the Quadratic Error simplification algorithm.
  70246. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70247. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70248. * @author RaananW
  70249. */
  70250. var QuadraticErrorSimplification = /** @class */ (function () {
  70251. function QuadraticErrorSimplification(_mesh) {
  70252. this._mesh = _mesh;
  70253. this.initialized = false;
  70254. this.syncIterations = 5000;
  70255. this.aggressiveness = 7;
  70256. this.decimationIterations = 100;
  70257. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70258. }
  70259. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70260. var _this = this;
  70261. this.initDecimatedMesh();
  70262. //iterating through the submeshes array, one after the other.
  70263. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70264. _this.initWithMesh(loop.index, function () {
  70265. _this.runDecimation(settings, loop.index, function () {
  70266. loop.executeNext();
  70267. });
  70268. }, settings.optimizeMesh);
  70269. }, function () {
  70270. setTimeout(function () {
  70271. successCallback(_this._reconstructedMesh);
  70272. }, 0);
  70273. });
  70274. };
  70275. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70276. var _this = this;
  70277. var targetCount = ~~(this.triangles.length * settings.quality);
  70278. var deletedTriangles = 0;
  70279. var triangleCount = this.triangles.length;
  70280. var iterationFunction = function (iteration, callback) {
  70281. setTimeout(function () {
  70282. if (iteration % 5 === 0) {
  70283. _this.updateMesh(iteration === 0);
  70284. }
  70285. for (var i = 0; i < _this.triangles.length; ++i) {
  70286. _this.triangles[i].isDirty = false;
  70287. }
  70288. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70289. var trianglesIterator = function (i) {
  70290. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70291. var t = _this.triangles[tIdx];
  70292. if (!t)
  70293. return;
  70294. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70295. return;
  70296. }
  70297. for (var j = 0; j < 3; ++j) {
  70298. if (t.error[j] < threshold) {
  70299. var deleted0 = [];
  70300. var deleted1 = [];
  70301. var v0 = t.vertices[j];
  70302. var v1 = t.vertices[(j + 1) % 3];
  70303. if (v0.isBorder || v1.isBorder)
  70304. continue;
  70305. var p = BABYLON.Vector3.Zero();
  70306. var n = BABYLON.Vector3.Zero();
  70307. var uv = BABYLON.Vector2.Zero();
  70308. var color = new BABYLON.Color4(0, 0, 0, 1);
  70309. _this.calculateError(v0, v1, p, n, uv, color);
  70310. var delTr = new Array();
  70311. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70312. continue;
  70313. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70314. continue;
  70315. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70316. continue;
  70317. var uniqueArray = new Array();
  70318. delTr.forEach(function (deletedT) {
  70319. if (uniqueArray.indexOf(deletedT) === -1) {
  70320. deletedT.deletePending = true;
  70321. uniqueArray.push(deletedT);
  70322. }
  70323. });
  70324. if (uniqueArray.length % 2 !== 0) {
  70325. continue;
  70326. }
  70327. v0.q = v1.q.add(v0.q);
  70328. v0.updatePosition(p);
  70329. var tStart = _this.references.length;
  70330. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70331. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70332. var tCount = _this.references.length - tStart;
  70333. if (tCount <= v0.triangleCount) {
  70334. if (tCount) {
  70335. for (var c = 0; c < tCount; c++) {
  70336. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70337. }
  70338. }
  70339. }
  70340. else {
  70341. v0.triangleStart = tStart;
  70342. }
  70343. v0.triangleCount = tCount;
  70344. break;
  70345. }
  70346. }
  70347. };
  70348. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70349. }, 0);
  70350. };
  70351. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70352. if (triangleCount - deletedTriangles <= targetCount)
  70353. loop.breakLoop();
  70354. else {
  70355. iterationFunction(loop.index, function () {
  70356. loop.executeNext();
  70357. });
  70358. }
  70359. }, function () {
  70360. setTimeout(function () {
  70361. //reconstruct this part of the mesh
  70362. _this.reconstructMesh(submeshIndex);
  70363. successCallback();
  70364. }, 0);
  70365. });
  70366. };
  70367. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70368. var _this = this;
  70369. this.vertices = [];
  70370. this.triangles = [];
  70371. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70372. var indices = this._mesh.getIndices();
  70373. var submesh = this._mesh.subMeshes[submeshIndex];
  70374. var findInVertices = function (positionToSearch) {
  70375. if (optimizeMesh) {
  70376. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70377. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70378. return _this.vertices[ii];
  70379. }
  70380. }
  70381. }
  70382. return null;
  70383. };
  70384. var vertexReferences = [];
  70385. var vertexInit = function (i) {
  70386. if (!positionData) {
  70387. return;
  70388. }
  70389. var offset = i + submesh.verticesStart;
  70390. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70391. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70392. vertex.originalOffsets.push(offset);
  70393. if (vertex.id === _this.vertices.length) {
  70394. _this.vertices.push(vertex);
  70395. }
  70396. vertexReferences.push(vertex.id);
  70397. };
  70398. //var totalVertices = mesh.getTotalVertices();
  70399. var totalVertices = submesh.verticesCount;
  70400. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70401. var indicesInit = function (i) {
  70402. if (!indices) {
  70403. return;
  70404. }
  70405. var offset = (submesh.indexStart / 3) + i;
  70406. var pos = (offset * 3);
  70407. var i0 = indices[pos + 0];
  70408. var i1 = indices[pos + 1];
  70409. var i2 = indices[pos + 2];
  70410. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70411. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70412. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70413. var triangle = new DecimationTriangle([v0, v1, v2]);
  70414. triangle.originalOffset = pos;
  70415. _this.triangles.push(triangle);
  70416. };
  70417. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70418. _this.init(callback);
  70419. });
  70420. });
  70421. };
  70422. QuadraticErrorSimplification.prototype.init = function (callback) {
  70423. var _this = this;
  70424. var triangleInit1 = function (i) {
  70425. var t = _this.triangles[i];
  70426. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70427. for (var j = 0; j < 3; j++) {
  70428. 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))));
  70429. }
  70430. };
  70431. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70432. var triangleInit2 = function (i) {
  70433. var t = _this.triangles[i];
  70434. for (var j = 0; j < 3; ++j) {
  70435. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70436. }
  70437. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70438. };
  70439. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70440. _this.initialized = true;
  70441. callback();
  70442. });
  70443. });
  70444. };
  70445. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  70446. var newTriangles = [];
  70447. var i;
  70448. for (i = 0; i < this.vertices.length; ++i) {
  70449. this.vertices[i].triangleCount = 0;
  70450. }
  70451. var t;
  70452. var j;
  70453. for (i = 0; i < this.triangles.length; ++i) {
  70454. if (!this.triangles[i].deleted) {
  70455. t = this.triangles[i];
  70456. for (j = 0; j < 3; ++j) {
  70457. t.vertices[j].triangleCount = 1;
  70458. }
  70459. newTriangles.push(t);
  70460. }
  70461. }
  70462. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  70463. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  70464. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  70465. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  70466. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70467. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70468. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70469. var vertexCount = 0;
  70470. for (i = 0; i < this.vertices.length; ++i) {
  70471. var vertex = this.vertices[i];
  70472. vertex.id = vertexCount;
  70473. if (vertex.triangleCount) {
  70474. vertex.originalOffsets.forEach(function (originalOffset) {
  70475. if (!normalData) {
  70476. return;
  70477. }
  70478. newPositionData.push(vertex.position.x);
  70479. newPositionData.push(vertex.position.y);
  70480. newPositionData.push(vertex.position.z);
  70481. newNormalData.push(normalData[originalOffset * 3]);
  70482. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  70483. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  70484. if (uvs && uvs.length) {
  70485. newUVsData.push(uvs[(originalOffset * 2)]);
  70486. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  70487. }
  70488. else if (colorsData && colorsData.length) {
  70489. newColorsData.push(colorsData[(originalOffset * 4)]);
  70490. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  70491. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  70492. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  70493. }
  70494. ++vertexCount;
  70495. });
  70496. }
  70497. }
  70498. var startingIndex = this._reconstructedMesh.getTotalIndices();
  70499. var startingVertex = this._reconstructedMesh.getTotalVertices();
  70500. var submeshesArray = this._reconstructedMesh.subMeshes;
  70501. this._reconstructedMesh.subMeshes = [];
  70502. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  70503. var originalIndices = this._mesh.getIndices();
  70504. for (i = 0; i < newTriangles.length; ++i) {
  70505. t = newTriangles[i]; //now get the new referencing point for each vertex
  70506. [0, 1, 2].forEach(function (idx) {
  70507. var id = originalIndices[t.originalOffset + idx];
  70508. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  70509. if (offset < 0)
  70510. offset = 0;
  70511. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  70512. });
  70513. }
  70514. //overwriting the old vertex buffers and indices.
  70515. this._reconstructedMesh.setIndices(newIndicesArray);
  70516. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  70517. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  70518. if (newUVsData.length > 0)
  70519. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  70520. if (newColorsData.length > 0)
  70521. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  70522. //create submesh
  70523. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  70524. if (submeshIndex > 0) {
  70525. this._reconstructedMesh.subMeshes = [];
  70526. submeshesArray.forEach(function (submesh) {
  70527. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  70528. });
  70529. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  70530. }
  70531. };
  70532. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  70533. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  70534. this._reconstructedMesh.material = this._mesh.material;
  70535. this._reconstructedMesh.parent = this._mesh.parent;
  70536. this._reconstructedMesh.isVisible = false;
  70537. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  70538. };
  70539. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  70540. for (var i = 0; i < vertex1.triangleCount; ++i) {
  70541. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  70542. if (t.deleted)
  70543. continue;
  70544. var s = this.references[vertex1.triangleStart + i].vertexId;
  70545. var v1 = t.vertices[(s + 1) % 3];
  70546. var v2 = t.vertices[(s + 2) % 3];
  70547. if ((v1 === vertex2 || v2 === vertex2)) {
  70548. deletedArray[i] = true;
  70549. delTr.push(t);
  70550. continue;
  70551. }
  70552. var d1 = v1.position.subtract(point);
  70553. d1 = d1.normalize();
  70554. var d2 = v2.position.subtract(point);
  70555. d2 = d2.normalize();
  70556. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  70557. return true;
  70558. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  70559. deletedArray[i] = false;
  70560. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  70561. return true;
  70562. }
  70563. return false;
  70564. };
  70565. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  70566. var newDeleted = deletedTriangles;
  70567. for (var i = 0; i < vertex.triangleCount; ++i) {
  70568. var ref = this.references[vertex.triangleStart + i];
  70569. var t = this.triangles[ref.triangleId];
  70570. if (t.deleted)
  70571. continue;
  70572. if (deletedArray[i] && t.deletePending) {
  70573. t.deleted = true;
  70574. newDeleted++;
  70575. continue;
  70576. }
  70577. t.vertices[ref.vertexId] = origVertex;
  70578. t.isDirty = true;
  70579. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  70580. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  70581. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  70582. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70583. this.references.push(ref);
  70584. }
  70585. return newDeleted;
  70586. };
  70587. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  70588. for (var i = 0; i < this.vertices.length; ++i) {
  70589. var vCount = [];
  70590. var vId = [];
  70591. var v = this.vertices[i];
  70592. var j;
  70593. for (j = 0; j < v.triangleCount; ++j) {
  70594. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  70595. for (var ii = 0; ii < 3; ii++) {
  70596. var ofs = 0;
  70597. var vv = triangle.vertices[ii];
  70598. while (ofs < vCount.length) {
  70599. if (vId[ofs] === vv.id)
  70600. break;
  70601. ++ofs;
  70602. }
  70603. if (ofs === vCount.length) {
  70604. vCount.push(1);
  70605. vId.push(vv.id);
  70606. }
  70607. else {
  70608. vCount[ofs]++;
  70609. }
  70610. }
  70611. }
  70612. for (j = 0; j < vCount.length; ++j) {
  70613. if (vCount[j] === 1) {
  70614. this.vertices[vId[j]].isBorder = true;
  70615. }
  70616. else {
  70617. this.vertices[vId[j]].isBorder = false;
  70618. }
  70619. }
  70620. }
  70621. };
  70622. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  70623. if (identifyBorders === void 0) { identifyBorders = false; }
  70624. var i;
  70625. if (!identifyBorders) {
  70626. var newTrianglesVector = [];
  70627. for (i = 0; i < this.triangles.length; ++i) {
  70628. if (!this.triangles[i].deleted) {
  70629. newTrianglesVector.push(this.triangles[i]);
  70630. }
  70631. }
  70632. this.triangles = newTrianglesVector;
  70633. }
  70634. for (i = 0; i < this.vertices.length; ++i) {
  70635. this.vertices[i].triangleCount = 0;
  70636. this.vertices[i].triangleStart = 0;
  70637. }
  70638. var t;
  70639. var j;
  70640. var v;
  70641. for (i = 0; i < this.triangles.length; ++i) {
  70642. t = this.triangles[i];
  70643. for (j = 0; j < 3; ++j) {
  70644. v = t.vertices[j];
  70645. v.triangleCount++;
  70646. }
  70647. }
  70648. var tStart = 0;
  70649. for (i = 0; i < this.vertices.length; ++i) {
  70650. this.vertices[i].triangleStart = tStart;
  70651. tStart += this.vertices[i].triangleCount;
  70652. this.vertices[i].triangleCount = 0;
  70653. }
  70654. var newReferences = new Array(this.triangles.length * 3);
  70655. for (i = 0; i < this.triangles.length; ++i) {
  70656. t = this.triangles[i];
  70657. for (j = 0; j < 3; ++j) {
  70658. v = t.vertices[j];
  70659. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  70660. v.triangleCount++;
  70661. }
  70662. }
  70663. this.references = newReferences;
  70664. if (identifyBorders) {
  70665. this.identifyBorder();
  70666. }
  70667. };
  70668. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  70669. var x = point.x;
  70670. var y = point.y;
  70671. var z = point.z;
  70672. 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
  70673. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  70674. };
  70675. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  70676. var q = vertex1.q.add(vertex2.q);
  70677. var border = vertex1.isBorder && vertex2.isBorder;
  70678. var error = 0;
  70679. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  70680. if (qDet !== 0 && !border) {
  70681. if (!pointResult) {
  70682. pointResult = BABYLON.Vector3.Zero();
  70683. }
  70684. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  70685. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  70686. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  70687. error = this.vertexError(q, pointResult);
  70688. }
  70689. else {
  70690. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  70691. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  70692. var error1 = this.vertexError(q, vertex1.position);
  70693. var error2 = this.vertexError(q, vertex2.position);
  70694. var error3 = this.vertexError(q, p3);
  70695. error = Math.min(error1, error2, error3);
  70696. if (error === error1) {
  70697. if (pointResult) {
  70698. pointResult.copyFrom(vertex1.position);
  70699. }
  70700. }
  70701. else if (error === error2) {
  70702. if (pointResult) {
  70703. pointResult.copyFrom(vertex2.position);
  70704. }
  70705. }
  70706. else {
  70707. if (pointResult) {
  70708. pointResult.copyFrom(p3);
  70709. }
  70710. }
  70711. }
  70712. return error;
  70713. };
  70714. return QuadraticErrorSimplification;
  70715. }());
  70716. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  70717. })(BABYLON || (BABYLON = {}));
  70718. //# sourceMappingURL=babylon.meshSimplification.js.map
  70719. var BABYLON;
  70720. (function (BABYLON) {
  70721. var Internals;
  70722. (function (Internals) {
  70723. var MeshLODLevel = /** @class */ (function () {
  70724. function MeshLODLevel(distance, mesh) {
  70725. this.distance = distance;
  70726. this.mesh = mesh;
  70727. }
  70728. return MeshLODLevel;
  70729. }());
  70730. Internals.MeshLODLevel = MeshLODLevel;
  70731. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70732. })(BABYLON || (BABYLON = {}));
  70733. //# sourceMappingURL=babylon.meshLODLevel.js.map
  70734. var BABYLON;
  70735. (function (BABYLON) {
  70736. // Standard optimizations
  70737. var SceneOptimization = /** @class */ (function () {
  70738. function SceneOptimization(priority) {
  70739. if (priority === void 0) { priority = 0; }
  70740. this.priority = priority;
  70741. this.apply = function (scene) {
  70742. return true; // Return true if everything that can be done was applied
  70743. };
  70744. }
  70745. return SceneOptimization;
  70746. }());
  70747. BABYLON.SceneOptimization = SceneOptimization;
  70748. var TextureOptimization = /** @class */ (function (_super) {
  70749. __extends(TextureOptimization, _super);
  70750. function TextureOptimization(priority, maximumSize) {
  70751. if (priority === void 0) { priority = 0; }
  70752. if (maximumSize === void 0) { maximumSize = 1024; }
  70753. var _this = _super.call(this, priority) || this;
  70754. _this.priority = priority;
  70755. _this.maximumSize = maximumSize;
  70756. _this.apply = function (scene) {
  70757. var allDone = true;
  70758. for (var index = 0; index < scene.textures.length; index++) {
  70759. var texture = scene.textures[index];
  70760. if (!texture.canRescale || texture.getContext) {
  70761. continue;
  70762. }
  70763. var currentSize = texture.getSize();
  70764. var maxDimension = Math.max(currentSize.width, currentSize.height);
  70765. if (maxDimension > _this.maximumSize) {
  70766. texture.scale(0.5);
  70767. allDone = false;
  70768. }
  70769. }
  70770. return allDone;
  70771. };
  70772. return _this;
  70773. }
  70774. return TextureOptimization;
  70775. }(SceneOptimization));
  70776. BABYLON.TextureOptimization = TextureOptimization;
  70777. var HardwareScalingOptimization = /** @class */ (function (_super) {
  70778. __extends(HardwareScalingOptimization, _super);
  70779. function HardwareScalingOptimization(priority, maximumScale) {
  70780. if (priority === void 0) { priority = 0; }
  70781. if (maximumScale === void 0) { maximumScale = 2; }
  70782. var _this = _super.call(this, priority) || this;
  70783. _this.priority = priority;
  70784. _this.maximumScale = maximumScale;
  70785. _this._currentScale = 1;
  70786. _this.apply = function (scene) {
  70787. _this._currentScale++;
  70788. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  70789. return _this._currentScale >= _this.maximumScale;
  70790. };
  70791. return _this;
  70792. }
  70793. return HardwareScalingOptimization;
  70794. }(SceneOptimization));
  70795. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  70796. var ShadowsOptimization = /** @class */ (function (_super) {
  70797. __extends(ShadowsOptimization, _super);
  70798. function ShadowsOptimization() {
  70799. var _this = _super !== null && _super.apply(this, arguments) || this;
  70800. _this.apply = function (scene) {
  70801. scene.shadowsEnabled = false;
  70802. return true;
  70803. };
  70804. return _this;
  70805. }
  70806. return ShadowsOptimization;
  70807. }(SceneOptimization));
  70808. BABYLON.ShadowsOptimization = ShadowsOptimization;
  70809. var PostProcessesOptimization = /** @class */ (function (_super) {
  70810. __extends(PostProcessesOptimization, _super);
  70811. function PostProcessesOptimization() {
  70812. var _this = _super !== null && _super.apply(this, arguments) || this;
  70813. _this.apply = function (scene) {
  70814. scene.postProcessesEnabled = false;
  70815. return true;
  70816. };
  70817. return _this;
  70818. }
  70819. return PostProcessesOptimization;
  70820. }(SceneOptimization));
  70821. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  70822. var LensFlaresOptimization = /** @class */ (function (_super) {
  70823. __extends(LensFlaresOptimization, _super);
  70824. function LensFlaresOptimization() {
  70825. var _this = _super !== null && _super.apply(this, arguments) || this;
  70826. _this.apply = function (scene) {
  70827. scene.lensFlaresEnabled = false;
  70828. return true;
  70829. };
  70830. return _this;
  70831. }
  70832. return LensFlaresOptimization;
  70833. }(SceneOptimization));
  70834. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  70835. var ParticlesOptimization = /** @class */ (function (_super) {
  70836. __extends(ParticlesOptimization, _super);
  70837. function ParticlesOptimization() {
  70838. var _this = _super !== null && _super.apply(this, arguments) || this;
  70839. _this.apply = function (scene) {
  70840. scene.particlesEnabled = false;
  70841. return true;
  70842. };
  70843. return _this;
  70844. }
  70845. return ParticlesOptimization;
  70846. }(SceneOptimization));
  70847. BABYLON.ParticlesOptimization = ParticlesOptimization;
  70848. var RenderTargetsOptimization = /** @class */ (function (_super) {
  70849. __extends(RenderTargetsOptimization, _super);
  70850. function RenderTargetsOptimization() {
  70851. var _this = _super !== null && _super.apply(this, arguments) || this;
  70852. _this.apply = function (scene) {
  70853. scene.renderTargetsEnabled = false;
  70854. return true;
  70855. };
  70856. return _this;
  70857. }
  70858. return RenderTargetsOptimization;
  70859. }(SceneOptimization));
  70860. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  70861. var MergeMeshesOptimization = /** @class */ (function (_super) {
  70862. __extends(MergeMeshesOptimization, _super);
  70863. function MergeMeshesOptimization() {
  70864. var _this = _super !== null && _super.apply(this, arguments) || this;
  70865. _this._canBeMerged = function (abstractMesh) {
  70866. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  70867. return false;
  70868. }
  70869. var mesh = abstractMesh;
  70870. if (!mesh.isVisible || !mesh.isEnabled()) {
  70871. return false;
  70872. }
  70873. if (mesh.instances.length > 0) {
  70874. return false;
  70875. }
  70876. if (mesh.skeleton || mesh.hasLODLevels) {
  70877. return false;
  70878. }
  70879. if (mesh.parent) {
  70880. return false;
  70881. }
  70882. return true;
  70883. };
  70884. _this.apply = function (scene, updateSelectionTree) {
  70885. var globalPool = scene.meshes.slice(0);
  70886. var globalLength = globalPool.length;
  70887. for (var index = 0; index < globalLength; index++) {
  70888. var currentPool = new Array();
  70889. var current = globalPool[index];
  70890. // Checks
  70891. if (!_this._canBeMerged(current)) {
  70892. continue;
  70893. }
  70894. currentPool.push(current);
  70895. // Find compatible meshes
  70896. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  70897. var otherMesh = globalPool[subIndex];
  70898. if (!_this._canBeMerged(otherMesh)) {
  70899. continue;
  70900. }
  70901. if (otherMesh.material !== current.material) {
  70902. continue;
  70903. }
  70904. if (otherMesh.checkCollisions !== current.checkCollisions) {
  70905. continue;
  70906. }
  70907. currentPool.push(otherMesh);
  70908. globalLength--;
  70909. globalPool.splice(subIndex, 1);
  70910. subIndex--;
  70911. }
  70912. if (currentPool.length < 2) {
  70913. continue;
  70914. }
  70915. // Merge meshes
  70916. BABYLON.Mesh.MergeMeshes(currentPool);
  70917. }
  70918. if (updateSelectionTree != undefined) {
  70919. if (updateSelectionTree) {
  70920. scene.createOrUpdateSelectionOctree();
  70921. }
  70922. }
  70923. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  70924. scene.createOrUpdateSelectionOctree();
  70925. }
  70926. return true;
  70927. };
  70928. return _this;
  70929. }
  70930. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  70931. get: function () {
  70932. return MergeMeshesOptimization._UpdateSelectionTree;
  70933. },
  70934. set: function (value) {
  70935. MergeMeshesOptimization._UpdateSelectionTree = value;
  70936. },
  70937. enumerable: true,
  70938. configurable: true
  70939. });
  70940. MergeMeshesOptimization._UpdateSelectionTree = false;
  70941. return MergeMeshesOptimization;
  70942. }(SceneOptimization));
  70943. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  70944. // Options
  70945. var SceneOptimizerOptions = /** @class */ (function () {
  70946. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  70947. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  70948. if (trackerDuration === void 0) { trackerDuration = 2000; }
  70949. this.targetFrameRate = targetFrameRate;
  70950. this.trackerDuration = trackerDuration;
  70951. this.optimizations = new Array();
  70952. }
  70953. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  70954. var result = new SceneOptimizerOptions(targetFrameRate);
  70955. var priority = 0;
  70956. result.optimizations.push(new MergeMeshesOptimization(priority));
  70957. result.optimizations.push(new ShadowsOptimization(priority));
  70958. result.optimizations.push(new LensFlaresOptimization(priority));
  70959. // Next priority
  70960. priority++;
  70961. result.optimizations.push(new PostProcessesOptimization(priority));
  70962. result.optimizations.push(new ParticlesOptimization(priority));
  70963. // Next priority
  70964. priority++;
  70965. result.optimizations.push(new TextureOptimization(priority, 1024));
  70966. return result;
  70967. };
  70968. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  70969. var result = new SceneOptimizerOptions(targetFrameRate);
  70970. var priority = 0;
  70971. result.optimizations.push(new MergeMeshesOptimization(priority));
  70972. result.optimizations.push(new ShadowsOptimization(priority));
  70973. result.optimizations.push(new LensFlaresOptimization(priority));
  70974. // Next priority
  70975. priority++;
  70976. result.optimizations.push(new PostProcessesOptimization(priority));
  70977. result.optimizations.push(new ParticlesOptimization(priority));
  70978. // Next priority
  70979. priority++;
  70980. result.optimizations.push(new TextureOptimization(priority, 512));
  70981. // Next priority
  70982. priority++;
  70983. result.optimizations.push(new RenderTargetsOptimization(priority));
  70984. // Next priority
  70985. priority++;
  70986. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  70987. return result;
  70988. };
  70989. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  70990. var result = new SceneOptimizerOptions(targetFrameRate);
  70991. var priority = 0;
  70992. result.optimizations.push(new MergeMeshesOptimization(priority));
  70993. result.optimizations.push(new ShadowsOptimization(priority));
  70994. result.optimizations.push(new LensFlaresOptimization(priority));
  70995. // Next priority
  70996. priority++;
  70997. result.optimizations.push(new PostProcessesOptimization(priority));
  70998. result.optimizations.push(new ParticlesOptimization(priority));
  70999. // Next priority
  71000. priority++;
  71001. result.optimizations.push(new TextureOptimization(priority, 256));
  71002. // Next priority
  71003. priority++;
  71004. result.optimizations.push(new RenderTargetsOptimization(priority));
  71005. // Next priority
  71006. priority++;
  71007. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71008. return result;
  71009. };
  71010. return SceneOptimizerOptions;
  71011. }());
  71012. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71013. // Scene optimizer tool
  71014. var SceneOptimizer = /** @class */ (function () {
  71015. function SceneOptimizer() {
  71016. }
  71017. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71018. // TODO: add an epsilon
  71019. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71020. if (onSuccess) {
  71021. onSuccess();
  71022. }
  71023. return;
  71024. }
  71025. // Apply current level of optimizations
  71026. var allDone = true;
  71027. var noOptimizationApplied = true;
  71028. for (var index = 0; index < options.optimizations.length; index++) {
  71029. var optimization = options.optimizations[index];
  71030. if (optimization.priority === currentPriorityLevel) {
  71031. noOptimizationApplied = false;
  71032. allDone = allDone && optimization.apply(scene);
  71033. }
  71034. }
  71035. // If no optimization was applied, this is a failure :(
  71036. if (noOptimizationApplied) {
  71037. if (onFailure) {
  71038. onFailure();
  71039. }
  71040. return;
  71041. }
  71042. // If all optimizations were done, move to next level
  71043. if (allDone) {
  71044. currentPriorityLevel++;
  71045. }
  71046. // Let's the system running for a specific amount of time before checking FPS
  71047. scene.executeWhenReady(function () {
  71048. setTimeout(function () {
  71049. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71050. }, options.trackerDuration);
  71051. });
  71052. };
  71053. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71054. if (!options) {
  71055. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71056. }
  71057. // Let's the system running for a specific amount of time before checking FPS
  71058. scene.executeWhenReady(function () {
  71059. setTimeout(function () {
  71060. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71061. }, options.trackerDuration);
  71062. });
  71063. };
  71064. return SceneOptimizer;
  71065. }());
  71066. BABYLON.SceneOptimizer = SceneOptimizer;
  71067. })(BABYLON || (BABYLON = {}));
  71068. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71069. var BABYLON;
  71070. (function (BABYLON) {
  71071. var OutlineRenderer = /** @class */ (function () {
  71072. function OutlineRenderer(scene) {
  71073. this.zOffset = 1;
  71074. this._scene = scene;
  71075. }
  71076. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71077. var _this = this;
  71078. if (useOverlay === void 0) { useOverlay = false; }
  71079. var scene = this._scene;
  71080. var engine = this._scene.getEngine();
  71081. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71082. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71083. return;
  71084. }
  71085. var mesh = subMesh.getRenderingMesh();
  71086. var material = subMesh.getMaterial();
  71087. if (!material || !scene.activeCamera) {
  71088. return;
  71089. }
  71090. engine.enableEffect(this._effect);
  71091. // Logarithmic depth
  71092. if (material.useLogarithmicDepth) {
  71093. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71094. }
  71095. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71096. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71097. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71098. // Bones
  71099. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71100. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71101. }
  71102. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71103. // Alpha test
  71104. if (material && material.needAlphaTesting()) {
  71105. var alphaTexture = material.getAlphaTestTexture();
  71106. if (alphaTexture) {
  71107. this._effect.setTexture("diffuseSampler", alphaTexture);
  71108. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71109. }
  71110. }
  71111. engine.setZOffset(-this.zOffset);
  71112. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71113. engine.setZOffset(0);
  71114. };
  71115. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71116. var defines = [];
  71117. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71118. var mesh = subMesh.getMesh();
  71119. var material = subMesh.getMaterial();
  71120. if (material) {
  71121. // Alpha test
  71122. if (material.needAlphaTesting()) {
  71123. defines.push("#define ALPHATEST");
  71124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71125. attribs.push(BABYLON.VertexBuffer.UVKind);
  71126. defines.push("#define UV1");
  71127. }
  71128. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71129. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71130. defines.push("#define UV2");
  71131. }
  71132. }
  71133. //Logarithmic depth
  71134. if (material.useLogarithmicDepth) {
  71135. defines.push("#define LOGARITHMICDEPTH");
  71136. }
  71137. }
  71138. // Bones
  71139. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71142. if (mesh.numBoneInfluencers > 4) {
  71143. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71144. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71145. }
  71146. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71147. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71148. }
  71149. else {
  71150. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71151. }
  71152. // Instances
  71153. if (useInstances) {
  71154. defines.push("#define INSTANCES");
  71155. attribs.push("world0");
  71156. attribs.push("world1");
  71157. attribs.push("world2");
  71158. attribs.push("world3");
  71159. }
  71160. // Get correct effect
  71161. var join = defines.join("\n");
  71162. if (this._cachedDefines !== join) {
  71163. this._cachedDefines = join;
  71164. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71165. }
  71166. return this._effect.isReady();
  71167. };
  71168. return OutlineRenderer;
  71169. }());
  71170. BABYLON.OutlineRenderer = OutlineRenderer;
  71171. })(BABYLON || (BABYLON = {}));
  71172. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71173. var BABYLON;
  71174. (function (BABYLON) {
  71175. var FaceAdjacencies = /** @class */ (function () {
  71176. function FaceAdjacencies() {
  71177. this.edges = new Array();
  71178. this.edgesConnectedCount = 0;
  71179. }
  71180. return FaceAdjacencies;
  71181. }());
  71182. var EdgesRenderer = /** @class */ (function () {
  71183. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71184. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71185. if (epsilon === void 0) { epsilon = 0.95; }
  71186. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71187. this.edgesWidthScalerForOrthographic = 1000.0;
  71188. this.edgesWidthScalerForPerspective = 50.0;
  71189. this._linesPositions = new Array();
  71190. this._linesNormals = new Array();
  71191. this._linesIndices = new Array();
  71192. this._buffers = {};
  71193. this._checkVerticesInsteadOfIndices = false;
  71194. this._source = source;
  71195. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71196. this._epsilon = epsilon;
  71197. this._prepareRessources();
  71198. this._generateEdgesLines();
  71199. }
  71200. EdgesRenderer.prototype._prepareRessources = function () {
  71201. if (this._lineShader) {
  71202. return;
  71203. }
  71204. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71205. attributes: ["position", "normal"],
  71206. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71207. });
  71208. this._lineShader.disableDepthWrite = true;
  71209. this._lineShader.backFaceCulling = false;
  71210. };
  71211. EdgesRenderer.prototype._rebuild = function () {
  71212. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71213. if (buffer) {
  71214. buffer._rebuild();
  71215. }
  71216. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71217. if (buffer) {
  71218. buffer._rebuild();
  71219. }
  71220. var scene = this._source.getScene();
  71221. var engine = scene.getEngine();
  71222. this._ib = engine.createIndexBuffer(this._linesIndices);
  71223. };
  71224. EdgesRenderer.prototype.dispose = function () {
  71225. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71226. if (buffer) {
  71227. buffer.dispose();
  71228. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71229. }
  71230. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71231. if (buffer) {
  71232. buffer.dispose();
  71233. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71234. }
  71235. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71236. this._lineShader.dispose();
  71237. };
  71238. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71239. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71240. return 0;
  71241. }
  71242. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71243. return 1;
  71244. }
  71245. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71246. return 2;
  71247. }
  71248. return -1;
  71249. };
  71250. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71251. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71252. return 0;
  71253. }
  71254. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71255. return 1;
  71256. }
  71257. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71258. return 2;
  71259. }
  71260. return -1;
  71261. };
  71262. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71263. var needToCreateLine;
  71264. if (edge === undefined) {
  71265. needToCreateLine = true;
  71266. }
  71267. else {
  71268. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71269. needToCreateLine = dotProduct < this._epsilon;
  71270. }
  71271. if (needToCreateLine) {
  71272. var offset = this._linesPositions.length / 3;
  71273. var normal = p0.subtract(p1);
  71274. normal.normalize();
  71275. // Positions
  71276. this._linesPositions.push(p0.x);
  71277. this._linesPositions.push(p0.y);
  71278. this._linesPositions.push(p0.z);
  71279. this._linesPositions.push(p0.x);
  71280. this._linesPositions.push(p0.y);
  71281. this._linesPositions.push(p0.z);
  71282. this._linesPositions.push(p1.x);
  71283. this._linesPositions.push(p1.y);
  71284. this._linesPositions.push(p1.z);
  71285. this._linesPositions.push(p1.x);
  71286. this._linesPositions.push(p1.y);
  71287. this._linesPositions.push(p1.z);
  71288. // Normals
  71289. this._linesNormals.push(p1.x);
  71290. this._linesNormals.push(p1.y);
  71291. this._linesNormals.push(p1.z);
  71292. this._linesNormals.push(-1);
  71293. this._linesNormals.push(p1.x);
  71294. this._linesNormals.push(p1.y);
  71295. this._linesNormals.push(p1.z);
  71296. this._linesNormals.push(1);
  71297. this._linesNormals.push(p0.x);
  71298. this._linesNormals.push(p0.y);
  71299. this._linesNormals.push(p0.z);
  71300. this._linesNormals.push(-1);
  71301. this._linesNormals.push(p0.x);
  71302. this._linesNormals.push(p0.y);
  71303. this._linesNormals.push(p0.z);
  71304. this._linesNormals.push(1);
  71305. // Indices
  71306. this._linesIndices.push(offset);
  71307. this._linesIndices.push(offset + 1);
  71308. this._linesIndices.push(offset + 2);
  71309. this._linesIndices.push(offset);
  71310. this._linesIndices.push(offset + 2);
  71311. this._linesIndices.push(offset + 3);
  71312. }
  71313. };
  71314. EdgesRenderer.prototype._generateEdgesLines = function () {
  71315. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71316. var indices = this._source.getIndices();
  71317. if (!indices || !positions) {
  71318. return;
  71319. }
  71320. // First let's find adjacencies
  71321. var adjacencies = new Array();
  71322. var faceNormals = new Array();
  71323. var index;
  71324. var faceAdjacencies;
  71325. // Prepare faces
  71326. for (index = 0; index < indices.length; index += 3) {
  71327. faceAdjacencies = new FaceAdjacencies();
  71328. var p0Index = indices[index];
  71329. var p1Index = indices[index + 1];
  71330. var p2Index = indices[index + 2];
  71331. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71332. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71333. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71334. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71335. faceNormal.normalize();
  71336. faceNormals.push(faceNormal);
  71337. adjacencies.push(faceAdjacencies);
  71338. }
  71339. // Scan
  71340. for (index = 0; index < adjacencies.length; index++) {
  71341. faceAdjacencies = adjacencies[index];
  71342. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71343. var otherFaceAdjacencies = adjacencies[otherIndex];
  71344. if (faceAdjacencies.edgesConnectedCount === 3) {
  71345. break;
  71346. }
  71347. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71348. continue;
  71349. }
  71350. var otherP0 = indices[otherIndex * 3];
  71351. var otherP1 = indices[otherIndex * 3 + 1];
  71352. var otherP2 = indices[otherIndex * 3 + 2];
  71353. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71354. var otherEdgeIndex = 0;
  71355. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71356. continue;
  71357. }
  71358. switch (edgeIndex) {
  71359. case 0:
  71360. if (this._checkVerticesInsteadOfIndices) {
  71361. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71362. }
  71363. else {
  71364. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71365. }
  71366. break;
  71367. case 1:
  71368. if (this._checkVerticesInsteadOfIndices) {
  71369. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71370. }
  71371. else {
  71372. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71373. }
  71374. break;
  71375. case 2:
  71376. if (this._checkVerticesInsteadOfIndices) {
  71377. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71378. }
  71379. else {
  71380. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71381. }
  71382. break;
  71383. }
  71384. if (otherEdgeIndex === -1) {
  71385. continue;
  71386. }
  71387. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71388. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71389. faceAdjacencies.edgesConnectedCount++;
  71390. otherFaceAdjacencies.edgesConnectedCount++;
  71391. if (faceAdjacencies.edgesConnectedCount === 3) {
  71392. break;
  71393. }
  71394. }
  71395. }
  71396. }
  71397. // Create lines
  71398. for (index = 0; index < adjacencies.length; index++) {
  71399. // 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
  71400. var current = adjacencies[index];
  71401. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71402. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71403. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71404. }
  71405. // Merge into a single mesh
  71406. var engine = this._source.getScene().getEngine();
  71407. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71408. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71409. this._ib = engine.createIndexBuffer(this._linesIndices);
  71410. this._indicesCount = this._linesIndices.length;
  71411. };
  71412. EdgesRenderer.prototype.render = function () {
  71413. var scene = this._source.getScene();
  71414. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71415. return;
  71416. }
  71417. var engine = scene.getEngine();
  71418. this._lineShader._preBind();
  71419. // VBOs
  71420. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71421. scene.resetCachedMaterial();
  71422. this._lineShader.setColor4("color", this._source.edgesColor);
  71423. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71424. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71425. }
  71426. else {
  71427. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71428. }
  71429. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71430. this._lineShader.bind(this._source.getWorldMatrix());
  71431. // Draw order
  71432. engine.draw(true, 0, this._indicesCount);
  71433. this._lineShader.unbind();
  71434. engine.setDepthWrite(true);
  71435. };
  71436. return EdgesRenderer;
  71437. }());
  71438. BABYLON.EdgesRenderer = EdgesRenderer;
  71439. })(BABYLON || (BABYLON = {}));
  71440. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71441. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  71442. /// <reference path="..\Math\babylon.math.ts" />
  71443. var BABYLON;
  71444. (function (BABYLON) {
  71445. /**
  71446. * Special Glow Blur post process only blurring the alpha channel
  71447. * It enforces keeping the most luminous color in the color channel.
  71448. */
  71449. var GlowBlurPostProcess = /** @class */ (function (_super) {
  71450. __extends(GlowBlurPostProcess, _super);
  71451. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  71452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71453. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  71454. _this.direction = direction;
  71455. _this.kernel = kernel;
  71456. _this.onApplyObservable.add(function (effect) {
  71457. effect.setFloat2("screenSize", _this.width, _this.height);
  71458. effect.setVector2("direction", _this.direction);
  71459. effect.setFloat("blurWidth", _this.kernel);
  71460. });
  71461. return _this;
  71462. }
  71463. return GlowBlurPostProcess;
  71464. }(BABYLON.PostProcess));
  71465. /**
  71466. * The highlight layer Helps adding a glow effect around a mesh.
  71467. *
  71468. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  71469. * glowy meshes to your scene.
  71470. *
  71471. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  71472. */
  71473. var HighlightLayer = /** @class */ (function () {
  71474. /**
  71475. * Instantiates a new highlight Layer and references it to the scene..
  71476. * @param name The name of the layer
  71477. * @param scene The scene to use the layer in
  71478. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  71479. */
  71480. function HighlightLayer(name, scene, options) {
  71481. this.name = name;
  71482. this._vertexBuffers = {};
  71483. this._mainTextureDesiredSize = { width: 0, height: 0 };
  71484. this._meshes = {};
  71485. this._maxSize = 0;
  71486. this._shouldRender = false;
  71487. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  71488. this._excludedMeshes = {};
  71489. /**
  71490. * Specifies whether or not the inner glow is ACTIVE in the layer.
  71491. */
  71492. this.innerGlow = true;
  71493. /**
  71494. * Specifies whether or not the outer glow is ACTIVE in the layer.
  71495. */
  71496. this.outerGlow = true;
  71497. /**
  71498. * Specifies wether the highlight layer is enabled or not.
  71499. */
  71500. this.isEnabled = true;
  71501. /**
  71502. * An event triggered when the highlight layer has been disposed.
  71503. * @type {BABYLON.Observable}
  71504. */
  71505. this.onDisposeObservable = new BABYLON.Observable();
  71506. /**
  71507. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  71508. * @type {BABYLON.Observable}
  71509. */
  71510. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  71511. /**
  71512. * An event triggered when the highlight layer is being blurred.
  71513. * @type {BABYLON.Observable}
  71514. */
  71515. this.onBeforeBlurObservable = new BABYLON.Observable();
  71516. /**
  71517. * An event triggered when the highlight layer has been blurred.
  71518. * @type {BABYLON.Observable}
  71519. */
  71520. this.onAfterBlurObservable = new BABYLON.Observable();
  71521. /**
  71522. * An event triggered when the glowing blurred texture is being merged in the scene.
  71523. * @type {BABYLON.Observable}
  71524. */
  71525. this.onBeforeComposeObservable = new BABYLON.Observable();
  71526. /**
  71527. * An event triggered when the glowing blurred texture has been merged in the scene.
  71528. * @type {BABYLON.Observable}
  71529. */
  71530. this.onAfterComposeObservable = new BABYLON.Observable();
  71531. /**
  71532. * An event triggered when the highlight layer changes its size.
  71533. * @type {BABYLON.Observable}
  71534. */
  71535. this.onSizeChangedObservable = new BABYLON.Observable();
  71536. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71537. var engine = scene.getEngine();
  71538. this._engine = engine;
  71539. this._maxSize = this._engine.getCaps().maxTextureSize;
  71540. this._scene.highlightLayers.push(this);
  71541. // Warn on stencil.
  71542. if (!this._engine.isStencilEnable) {
  71543. 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 }");
  71544. }
  71545. // Adapt options
  71546. this._options = options || {
  71547. mainTextureRatio: 0.5,
  71548. blurTextureSizeRatio: 0.5,
  71549. blurHorizontalSize: 1.0,
  71550. blurVerticalSize: 1.0,
  71551. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  71552. camera: null
  71553. };
  71554. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  71555. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  71556. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  71557. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  71558. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  71559. // VBO
  71560. var vertices = [];
  71561. vertices.push(1, 1);
  71562. vertices.push(-1, 1);
  71563. vertices.push(-1, -1);
  71564. vertices.push(1, -1);
  71565. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71566. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71567. this._createIndexBuffer();
  71568. // Effect
  71569. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  71570. // Render target
  71571. this.setMainTextureSize();
  71572. // Create Textures and post processes
  71573. this.createTextureAndPostProcesses();
  71574. }
  71575. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  71576. /**
  71577. * Gets the horizontal size of the blur.
  71578. */
  71579. get: function () {
  71580. return this._horizontalBlurPostprocess.kernel;
  71581. },
  71582. /**
  71583. * Specifies the horizontal size of the blur.
  71584. */
  71585. set: function (value) {
  71586. this._horizontalBlurPostprocess.kernel = value;
  71587. },
  71588. enumerable: true,
  71589. configurable: true
  71590. });
  71591. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  71592. /**
  71593. * Gets the vertical size of the blur.
  71594. */
  71595. get: function () {
  71596. return this._verticalBlurPostprocess.kernel;
  71597. },
  71598. /**
  71599. * Specifies the vertical size of the blur.
  71600. */
  71601. set: function (value) {
  71602. this._verticalBlurPostprocess.kernel = value;
  71603. },
  71604. enumerable: true,
  71605. configurable: true
  71606. });
  71607. Object.defineProperty(HighlightLayer.prototype, "camera", {
  71608. /**
  71609. * Gets the camera attached to the layer.
  71610. */
  71611. get: function () {
  71612. return this._options.camera;
  71613. },
  71614. enumerable: true,
  71615. configurable: true
  71616. });
  71617. HighlightLayer.prototype._createIndexBuffer = function () {
  71618. var engine = this._scene.getEngine();
  71619. // Indices
  71620. var indices = [];
  71621. indices.push(0);
  71622. indices.push(1);
  71623. indices.push(2);
  71624. indices.push(0);
  71625. indices.push(2);
  71626. indices.push(3);
  71627. this._indexBuffer = engine.createIndexBuffer(indices);
  71628. };
  71629. HighlightLayer.prototype._rebuild = function () {
  71630. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71631. if (vb) {
  71632. vb._rebuild();
  71633. }
  71634. this._createIndexBuffer();
  71635. };
  71636. /**
  71637. * Creates the render target textures and post processes used in the highlight layer.
  71638. */
  71639. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  71640. var _this = this;
  71641. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  71642. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  71643. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  71644. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  71645. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  71646. width: this._mainTextureDesiredSize.width,
  71647. height: this._mainTextureDesiredSize.height
  71648. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71649. this._mainTexture.activeCamera = this._options.camera;
  71650. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71651. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71652. this._mainTexture.anisotropicFilteringLevel = 1;
  71653. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71654. this._mainTexture.renderParticles = false;
  71655. this._mainTexture.renderList = null;
  71656. this._mainTexture.ignoreCameraViewport = true;
  71657. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  71658. width: blurTextureWidth,
  71659. height: blurTextureHeight
  71660. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71661. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71662. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71663. this._blurTexture.anisotropicFilteringLevel = 16;
  71664. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71665. this._blurTexture.renderParticles = false;
  71666. this._blurTexture.ignoreCameraViewport = true;
  71667. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71668. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  71669. effect.setTexture("textureSampler", _this._mainTexture);
  71670. });
  71671. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  71672. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71673. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71674. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71675. });
  71676. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71677. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71678. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71679. });
  71680. }
  71681. else {
  71682. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71683. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71684. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71685. });
  71686. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71687. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71688. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71689. });
  71690. }
  71691. this._mainTexture.onAfterUnbindObservable.add(function () {
  71692. _this.onBeforeBlurObservable.notifyObservers(_this);
  71693. var internalTexture = _this._blurTexture.getInternalTexture();
  71694. if (internalTexture) {
  71695. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  71696. }
  71697. _this.onAfterBlurObservable.notifyObservers(_this);
  71698. });
  71699. // Custom render function
  71700. var renderSubMesh = function (subMesh) {
  71701. if (!_this._meshes) {
  71702. return;
  71703. }
  71704. var material = subMesh.getMaterial();
  71705. var mesh = subMesh.getRenderingMesh();
  71706. var scene = _this._scene;
  71707. var engine = scene.getEngine();
  71708. if (!material) {
  71709. return;
  71710. }
  71711. // Culling
  71712. engine.setState(material.backFaceCulling);
  71713. // Managing instances
  71714. var batch = mesh._getInstancesRenderList(subMesh._id);
  71715. if (batch.mustReturn) {
  71716. return;
  71717. }
  71718. // Excluded Mesh
  71719. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  71720. return;
  71721. }
  71722. ;
  71723. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71724. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  71725. var emissiveTexture = null;
  71726. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  71727. emissiveTexture = material.emissiveTexture;
  71728. }
  71729. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  71730. engine.enableEffect(_this._glowMapGenerationEffect);
  71731. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  71732. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  71733. if (highlightLayerMesh) {
  71734. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  71735. }
  71736. else {
  71737. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  71738. }
  71739. // Alpha test
  71740. if (material && material.needAlphaTesting()) {
  71741. var alphaTexture = material.getAlphaTestTexture();
  71742. if (alphaTexture) {
  71743. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  71744. var textureMatrix = alphaTexture.getTextureMatrix();
  71745. if (textureMatrix) {
  71746. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  71747. }
  71748. }
  71749. }
  71750. // Glow emissive only
  71751. if (emissiveTexture) {
  71752. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  71753. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  71754. }
  71755. // Bones
  71756. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71757. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71758. }
  71759. // Draw
  71760. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  71761. }
  71762. else {
  71763. // Need to reset refresh rate of the shadowMap
  71764. _this._mainTexture.resetRefreshCounter();
  71765. }
  71766. };
  71767. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71768. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  71769. var index;
  71770. var engine = _this._scene.getEngine();
  71771. if (depthOnlySubMeshes.length) {
  71772. engine.setColorWrite(false);
  71773. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71774. renderSubMesh(depthOnlySubMeshes.data[index]);
  71775. }
  71776. engine.setColorWrite(true);
  71777. }
  71778. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71779. renderSubMesh(opaqueSubMeshes.data[index]);
  71780. }
  71781. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71782. renderSubMesh(alphaTestSubMeshes.data[index]);
  71783. }
  71784. for (index = 0; index < transparentSubMeshes.length; index++) {
  71785. renderSubMesh(transparentSubMeshes.data[index]);
  71786. }
  71787. };
  71788. this._mainTexture.onClearObservable.add(function (engine) {
  71789. engine.clear(HighlightLayer.neutralColor, true, true, true);
  71790. });
  71791. };
  71792. /**
  71793. * Checks for the readiness of the element composing the layer.
  71794. * @param subMesh the mesh to check for
  71795. * @param useInstances specify wether or not to use instances to render the mesh
  71796. * @param emissiveTexture the associated emissive texture used to generate the glow
  71797. * @return true if ready otherwise, false
  71798. */
  71799. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  71800. var material = subMesh.getMaterial();
  71801. if (!material) {
  71802. return false;
  71803. }
  71804. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  71805. return false;
  71806. }
  71807. var defines = [];
  71808. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71809. var mesh = subMesh.getMesh();
  71810. var uv1 = false;
  71811. var uv2 = false;
  71812. // Alpha test
  71813. if (material && material.needAlphaTesting()) {
  71814. var alphaTexture = material.getAlphaTestTexture();
  71815. if (alphaTexture) {
  71816. defines.push("#define ALPHATEST");
  71817. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71818. alphaTexture.coordinatesIndex === 1) {
  71819. defines.push("#define DIFFUSEUV2");
  71820. uv2 = true;
  71821. }
  71822. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71823. defines.push("#define DIFFUSEUV1");
  71824. uv1 = true;
  71825. }
  71826. }
  71827. }
  71828. // Emissive
  71829. if (emissiveTexture) {
  71830. defines.push("#define EMISSIVE");
  71831. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71832. emissiveTexture.coordinatesIndex === 1) {
  71833. defines.push("#define EMISSIVEUV2");
  71834. uv2 = true;
  71835. }
  71836. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71837. defines.push("#define EMISSIVEUV1");
  71838. uv1 = true;
  71839. }
  71840. }
  71841. if (uv1) {
  71842. attribs.push(BABYLON.VertexBuffer.UVKind);
  71843. defines.push("#define UV1");
  71844. }
  71845. if (uv2) {
  71846. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71847. defines.push("#define UV2");
  71848. }
  71849. // Bones
  71850. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71851. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71852. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71853. if (mesh.numBoneInfluencers > 4) {
  71854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71856. }
  71857. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71858. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71859. }
  71860. else {
  71861. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71862. }
  71863. // Instances
  71864. if (useInstances) {
  71865. defines.push("#define INSTANCES");
  71866. attribs.push("world0");
  71867. attribs.push("world1");
  71868. attribs.push("world2");
  71869. attribs.push("world3");
  71870. }
  71871. // Get correct effect
  71872. var join = defines.join("\n");
  71873. if (this._cachedDefines !== join) {
  71874. this._cachedDefines = join;
  71875. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  71876. }
  71877. return this._glowMapGenerationEffect.isReady();
  71878. };
  71879. /**
  71880. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  71881. */
  71882. HighlightLayer.prototype.render = function () {
  71883. var currentEffect = this._glowMapMergeEffect;
  71884. // Check
  71885. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  71886. return;
  71887. var engine = this._scene.getEngine();
  71888. this.onBeforeComposeObservable.notifyObservers(this);
  71889. // Render
  71890. engine.enableEffect(currentEffect);
  71891. engine.setState(false);
  71892. // Cache
  71893. var previousStencilBuffer = engine.getStencilBuffer();
  71894. var previousStencilFunction = engine.getStencilFunction();
  71895. var previousStencilMask = engine.getStencilMask();
  71896. var previousStencilOperationPass = engine.getStencilOperationPass();
  71897. var previousStencilOperationFail = engine.getStencilOperationFail();
  71898. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  71899. var previousAlphaMode = engine.getAlphaMode();
  71900. // Texture
  71901. currentEffect.setTexture("textureSampler", this._blurTexture);
  71902. // VBOs
  71903. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  71904. // Stencil operations
  71905. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  71906. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  71907. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  71908. // Draw order
  71909. engine.setAlphaMode(this._options.alphaBlendingMode);
  71910. engine.setStencilMask(0x00);
  71911. engine.setStencilBuffer(true);
  71912. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  71913. if (this.outerGlow) {
  71914. currentEffect.setFloat("offset", 0);
  71915. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  71916. engine.draw(true, 0, 6);
  71917. }
  71918. if (this.innerGlow) {
  71919. currentEffect.setFloat("offset", 1);
  71920. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  71921. engine.draw(true, 0, 6);
  71922. }
  71923. // Restore Cache
  71924. engine.setStencilFunction(previousStencilFunction);
  71925. engine.setStencilMask(previousStencilMask);
  71926. engine.setAlphaMode(previousAlphaMode);
  71927. engine.setStencilBuffer(previousStencilBuffer);
  71928. engine.setStencilOperationPass(previousStencilOperationPass);
  71929. engine.setStencilOperationFail(previousStencilOperationFail);
  71930. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  71931. engine._stencilState.reset();
  71932. this.onAfterComposeObservable.notifyObservers(this);
  71933. // Handle size changes.
  71934. var size = this._mainTexture.getSize();
  71935. this.setMainTextureSize();
  71936. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  71937. // Recreate RTT and post processes on size change.
  71938. this.onSizeChangedObservable.notifyObservers(this);
  71939. this.disposeTextureAndPostProcesses();
  71940. this.createTextureAndPostProcesses();
  71941. }
  71942. };
  71943. /**
  71944. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  71945. * @param mesh The mesh to exclude from the highlight layer
  71946. */
  71947. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  71948. if (!this._excludedMeshes) {
  71949. return;
  71950. }
  71951. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  71952. if (!meshExcluded) {
  71953. this._excludedMeshes[mesh.uniqueId] = {
  71954. mesh: mesh,
  71955. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  71956. mesh.getEngine().setStencilBuffer(false);
  71957. }),
  71958. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  71959. mesh.getEngine().setStencilBuffer(true);
  71960. }),
  71961. };
  71962. }
  71963. };
  71964. /**
  71965. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  71966. * @param mesh The mesh to highlight
  71967. */
  71968. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  71969. if (!this._excludedMeshes) {
  71970. return;
  71971. }
  71972. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  71973. if (meshExcluded) {
  71974. if (meshExcluded.beforeRender) {
  71975. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  71976. }
  71977. if (meshExcluded.afterRender) {
  71978. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  71979. }
  71980. }
  71981. this._excludedMeshes[mesh.uniqueId] = null;
  71982. };
  71983. /**
  71984. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  71985. * @param mesh The mesh to highlight
  71986. * @param color The color of the highlight
  71987. * @param glowEmissiveOnly Extract the glow from the emissive texture
  71988. */
  71989. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  71990. var _this = this;
  71991. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  71992. if (!this._meshes) {
  71993. return;
  71994. }
  71995. var meshHighlight = this._meshes[mesh.uniqueId];
  71996. if (meshHighlight) {
  71997. meshHighlight.color = color;
  71998. }
  71999. else {
  72000. this._meshes[mesh.uniqueId] = {
  72001. mesh: mesh,
  72002. color: color,
  72003. // Lambda required for capture due to Observable this context
  72004. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72005. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72006. _this.defaultStencilReference(mesh);
  72007. }
  72008. else {
  72009. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72010. }
  72011. }),
  72012. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72013. glowEmissiveOnly: glowEmissiveOnly
  72014. };
  72015. }
  72016. this._shouldRender = true;
  72017. };
  72018. /**
  72019. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72020. * @param mesh The mesh to highlight
  72021. */
  72022. HighlightLayer.prototype.removeMesh = function (mesh) {
  72023. if (!this._meshes) {
  72024. return;
  72025. }
  72026. var meshHighlight = this._meshes[mesh.uniqueId];
  72027. if (meshHighlight) {
  72028. if (meshHighlight.observerHighlight) {
  72029. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72030. }
  72031. if (meshHighlight.observerDefault) {
  72032. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72033. }
  72034. }
  72035. this._meshes[mesh.uniqueId] = null;
  72036. this._shouldRender = false;
  72037. for (var meshHighlightToCheck in this._meshes) {
  72038. if (meshHighlightToCheck) {
  72039. this._shouldRender = true;
  72040. break;
  72041. }
  72042. }
  72043. };
  72044. /**
  72045. * Returns true if the layer contains information to display, otherwise false.
  72046. */
  72047. HighlightLayer.prototype.shouldRender = function () {
  72048. return this.isEnabled && this._shouldRender;
  72049. };
  72050. /**
  72051. * Sets the main texture desired size which is the closest power of two
  72052. * of the engine canvas size.
  72053. */
  72054. HighlightLayer.prototype.setMainTextureSize = function () {
  72055. if (this._options.mainTextureFixedSize) {
  72056. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72057. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72058. }
  72059. else {
  72060. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72061. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72062. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72063. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72064. }
  72065. };
  72066. /**
  72067. * Force the stencil to the normal expected value for none glowing parts
  72068. */
  72069. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72070. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72071. };
  72072. /**
  72073. * Dispose only the render target textures and post process.
  72074. */
  72075. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72076. this._blurTexture.dispose();
  72077. this._mainTexture.dispose();
  72078. this._downSamplePostprocess.dispose();
  72079. this._horizontalBlurPostprocess.dispose();
  72080. this._verticalBlurPostprocess.dispose();
  72081. };
  72082. /**
  72083. * Dispose the highlight layer and free resources.
  72084. */
  72085. HighlightLayer.prototype.dispose = function () {
  72086. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72087. if (vertexBuffer) {
  72088. vertexBuffer.dispose();
  72089. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72090. }
  72091. if (this._indexBuffer) {
  72092. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72093. this._indexBuffer = null;
  72094. }
  72095. // Clean textures and post processes
  72096. this.disposeTextureAndPostProcesses();
  72097. if (this._meshes) {
  72098. // Clean mesh references
  72099. for (var id in this._meshes) {
  72100. var meshHighlight = this._meshes[id];
  72101. if (meshHighlight && meshHighlight.mesh) {
  72102. if (meshHighlight.observerHighlight) {
  72103. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72104. }
  72105. if (meshHighlight.observerDefault) {
  72106. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72107. }
  72108. }
  72109. }
  72110. this._meshes = null;
  72111. }
  72112. if (this._excludedMeshes) {
  72113. for (var id in this._excludedMeshes) {
  72114. var meshHighlight = this._excludedMeshes[id];
  72115. if (meshHighlight) {
  72116. if (meshHighlight.beforeRender) {
  72117. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72118. }
  72119. if (meshHighlight.afterRender) {
  72120. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72121. }
  72122. }
  72123. }
  72124. this._excludedMeshes = null;
  72125. }
  72126. // Remove from scene
  72127. var index = this._scene.highlightLayers.indexOf(this, 0);
  72128. if (index > -1) {
  72129. this._scene.highlightLayers.splice(index, 1);
  72130. }
  72131. // Callback
  72132. this.onDisposeObservable.notifyObservers(this);
  72133. this.onDisposeObservable.clear();
  72134. this.onBeforeRenderMainTextureObservable.clear();
  72135. this.onBeforeBlurObservable.clear();
  72136. this.onBeforeComposeObservable.clear();
  72137. this.onAfterComposeObservable.clear();
  72138. this.onSizeChangedObservable.clear();
  72139. };
  72140. /**
  72141. * The neutral color used during the preparation of the glow effect.
  72142. * This is black by default as the blend operation is a blend operation.
  72143. */
  72144. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72145. /**
  72146. * Stencil value used for glowing meshes.
  72147. */
  72148. HighlightLayer.glowingMeshStencilReference = 0x02;
  72149. /**
  72150. * Stencil value used for the other meshes in the scene.
  72151. */
  72152. HighlightLayer.normalMeshStencilReference = 0x01;
  72153. return HighlightLayer;
  72154. }());
  72155. BABYLON.HighlightLayer = HighlightLayer;
  72156. })(BABYLON || (BABYLON = {}));
  72157. //# sourceMappingURL=babylon.highlightlayer.js.map
  72158. var BABYLON;
  72159. (function (BABYLON) {
  72160. var AssetTaskState;
  72161. (function (AssetTaskState) {
  72162. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72163. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72164. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72165. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72166. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72167. var AbstractAssetTask = /** @class */ (function () {
  72168. function AbstractAssetTask(name) {
  72169. this.name = name;
  72170. this.isCompleted = false;
  72171. this.taskState = AssetTaskState.INIT;
  72172. }
  72173. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72174. var _this = this;
  72175. this.taskState = AssetTaskState.RUNNING;
  72176. this.runTask(scene, function () {
  72177. _this.onDoneCallback(onSuccess, onError);
  72178. }, function (msg, exception) {
  72179. _this.onErrorCallback(onError, msg, exception);
  72180. });
  72181. };
  72182. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72183. throw new Error("runTask is not implemented");
  72184. };
  72185. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72186. this.taskState = AssetTaskState.ERROR;
  72187. this.errorObject = {
  72188. message: message,
  72189. exception: exception
  72190. };
  72191. if (this.onError) {
  72192. this.onError(this, message, exception);
  72193. }
  72194. onError();
  72195. };
  72196. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72197. try {
  72198. this.taskState = AssetTaskState.DONE;
  72199. this.isCompleted = true;
  72200. if (this.onSuccess) {
  72201. this.onSuccess(this);
  72202. }
  72203. onSuccess();
  72204. }
  72205. catch (e) {
  72206. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72207. }
  72208. };
  72209. return AbstractAssetTask;
  72210. }());
  72211. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72212. var MeshAssetTask = /** @class */ (function (_super) {
  72213. __extends(MeshAssetTask, _super);
  72214. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72215. var _this = _super.call(this, name) || this;
  72216. _this.name = name;
  72217. _this.meshesNames = meshesNames;
  72218. _this.rootUrl = rootUrl;
  72219. _this.sceneFilename = sceneFilename;
  72220. return _this;
  72221. }
  72222. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72223. var _this = this;
  72224. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72225. _this.loadedMeshes = meshes;
  72226. _this.loadedParticleSystems = particleSystems;
  72227. _this.loadedSkeletons = skeletons;
  72228. onSuccess();
  72229. }, null, function (scene, message, exception) {
  72230. onError(message, exception);
  72231. });
  72232. };
  72233. return MeshAssetTask;
  72234. }(AbstractAssetTask));
  72235. BABYLON.MeshAssetTask = MeshAssetTask;
  72236. var TextFileAssetTask = /** @class */ (function (_super) {
  72237. __extends(TextFileAssetTask, _super);
  72238. function TextFileAssetTask(name, url) {
  72239. var _this = _super.call(this, name) || this;
  72240. _this.name = name;
  72241. _this.url = url;
  72242. return _this;
  72243. }
  72244. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72245. var _this = this;
  72246. BABYLON.Tools.LoadFile(this.url, function (data) {
  72247. _this.text = data;
  72248. onSuccess();
  72249. }, undefined, scene.database, false, function (request, exception) {
  72250. if (request) {
  72251. onError(request.status + " " + request.statusText, exception);
  72252. }
  72253. });
  72254. };
  72255. return TextFileAssetTask;
  72256. }(AbstractAssetTask));
  72257. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72258. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72259. __extends(BinaryFileAssetTask, _super);
  72260. function BinaryFileAssetTask(name, url) {
  72261. var _this = _super.call(this, name) || this;
  72262. _this.name = name;
  72263. _this.url = url;
  72264. return _this;
  72265. }
  72266. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72267. var _this = this;
  72268. BABYLON.Tools.LoadFile(this.url, function (data) {
  72269. _this.data = data;
  72270. onSuccess();
  72271. }, undefined, scene.database, true, function (request, exception) {
  72272. if (request) {
  72273. onError(request.status + " " + request.statusText, exception);
  72274. }
  72275. });
  72276. };
  72277. return BinaryFileAssetTask;
  72278. }(AbstractAssetTask));
  72279. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72280. var ImageAssetTask = /** @class */ (function (_super) {
  72281. __extends(ImageAssetTask, _super);
  72282. function ImageAssetTask(name, url) {
  72283. var _this = _super.call(this, name) || this;
  72284. _this.name = name;
  72285. _this.url = url;
  72286. return _this;
  72287. }
  72288. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72289. var _this = this;
  72290. var img = new Image();
  72291. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72292. img.onload = function () {
  72293. _this.image = img;
  72294. onSuccess();
  72295. };
  72296. img.onerror = function (err) {
  72297. onError("Error loading image", err);
  72298. };
  72299. img.src = this.url;
  72300. };
  72301. return ImageAssetTask;
  72302. }(AbstractAssetTask));
  72303. BABYLON.ImageAssetTask = ImageAssetTask;
  72304. var TextureAssetTask = /** @class */ (function (_super) {
  72305. __extends(TextureAssetTask, _super);
  72306. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72307. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72308. var _this = _super.call(this, name) || this;
  72309. _this.name = name;
  72310. _this.url = url;
  72311. _this.noMipmap = noMipmap;
  72312. _this.invertY = invertY;
  72313. _this.samplingMode = samplingMode;
  72314. return _this;
  72315. }
  72316. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72317. var onload = function () {
  72318. onSuccess();
  72319. };
  72320. var onerror = function (msg, exception) {
  72321. onError(msg, exception);
  72322. };
  72323. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72324. };
  72325. return TextureAssetTask;
  72326. }(AbstractAssetTask));
  72327. BABYLON.TextureAssetTask = TextureAssetTask;
  72328. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72329. __extends(CubeTextureAssetTask, _super);
  72330. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72331. var _this = _super.call(this, name) || this;
  72332. _this.name = name;
  72333. _this.url = url;
  72334. _this.extensions = extensions;
  72335. _this.noMipmap = noMipmap;
  72336. _this.files = files;
  72337. return _this;
  72338. }
  72339. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72340. var onload = function () {
  72341. onSuccess();
  72342. };
  72343. var onerror = function (msg, exception) {
  72344. onError(msg, exception);
  72345. };
  72346. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72347. };
  72348. return CubeTextureAssetTask;
  72349. }(AbstractAssetTask));
  72350. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72351. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72352. __extends(HDRCubeTextureAssetTask, _super);
  72353. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72354. if (noMipmap === void 0) { noMipmap = false; }
  72355. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72356. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72357. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72358. var _this = _super.call(this, name) || this;
  72359. _this.name = name;
  72360. _this.url = url;
  72361. _this.size = size;
  72362. _this.noMipmap = noMipmap;
  72363. _this.generateHarmonics = generateHarmonics;
  72364. _this.useInGammaSpace = useInGammaSpace;
  72365. _this.usePMREMGenerator = usePMREMGenerator;
  72366. return _this;
  72367. }
  72368. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72369. var onload = function () {
  72370. onSuccess();
  72371. };
  72372. var onerror = function (message, exception) {
  72373. onError(message, exception);
  72374. };
  72375. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72376. };
  72377. return HDRCubeTextureAssetTask;
  72378. }(AbstractAssetTask));
  72379. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72380. var AssetsManager = /** @class */ (function () {
  72381. function AssetsManager(scene) {
  72382. this.tasks = new Array();
  72383. this.waitingTasksCount = 0;
  72384. //Observables
  72385. this.onTaskSuccessObservable = new BABYLON.Observable();
  72386. this.onTaskErrorObservable = new BABYLON.Observable();
  72387. this.onTasksDoneObservable = new BABYLON.Observable();
  72388. this.useDefaultLoadingScreen = true;
  72389. this._scene = scene;
  72390. }
  72391. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72392. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72393. this.tasks.push(task);
  72394. return task;
  72395. };
  72396. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72397. var task = new TextFileAssetTask(taskName, url);
  72398. this.tasks.push(task);
  72399. return task;
  72400. };
  72401. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72402. var task = new BinaryFileAssetTask(taskName, url);
  72403. this.tasks.push(task);
  72404. return task;
  72405. };
  72406. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72407. var task = new ImageAssetTask(taskName, url);
  72408. this.tasks.push(task);
  72409. return task;
  72410. };
  72411. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72413. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72414. this.tasks.push(task);
  72415. return task;
  72416. };
  72417. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72418. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72419. this.tasks.push(task);
  72420. return task;
  72421. };
  72422. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72423. if (noMipmap === void 0) { noMipmap = false; }
  72424. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72425. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72426. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72427. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72428. this.tasks.push(task);
  72429. return task;
  72430. };
  72431. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  72432. this.waitingTasksCount--;
  72433. if (this.waitingTasksCount === 0) {
  72434. try {
  72435. if (this.onFinish) {
  72436. this.onFinish(this.tasks);
  72437. }
  72438. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72439. }
  72440. catch (e) {
  72441. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  72442. console.log(e);
  72443. }
  72444. this._scene.getEngine().hideLoadingUI();
  72445. }
  72446. };
  72447. AssetsManager.prototype._runTask = function (task) {
  72448. var _this = this;
  72449. var done = function () {
  72450. try {
  72451. if (_this.onTaskSuccess) {
  72452. _this.onTaskSuccess(task);
  72453. }
  72454. _this.onTaskSuccessObservable.notifyObservers(task);
  72455. _this._decreaseWaitingTasksCount();
  72456. }
  72457. catch (e) {
  72458. error("Error executing task success callbacks", e);
  72459. }
  72460. };
  72461. var error = function (message, exception) {
  72462. task.errorObject = task.errorObject || {
  72463. message: message,
  72464. exception: exception
  72465. };
  72466. if (_this.onTaskError) {
  72467. _this.onTaskError(task);
  72468. }
  72469. _this.onTaskErrorObservable.notifyObservers(task);
  72470. _this._decreaseWaitingTasksCount();
  72471. };
  72472. task.run(this._scene, done, error);
  72473. };
  72474. AssetsManager.prototype.reset = function () {
  72475. this.tasks = new Array();
  72476. return this;
  72477. };
  72478. AssetsManager.prototype.load = function () {
  72479. this.waitingTasksCount = this.tasks.length;
  72480. if (this.waitingTasksCount === 0) {
  72481. if (this.onFinish) {
  72482. this.onFinish(this.tasks);
  72483. }
  72484. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72485. return this;
  72486. }
  72487. if (this.useDefaultLoadingScreen) {
  72488. this._scene.getEngine().displayLoadingUI();
  72489. }
  72490. for (var index = 0; index < this.tasks.length; index++) {
  72491. var task = this.tasks[index];
  72492. this._runTask(task);
  72493. }
  72494. return this;
  72495. };
  72496. return AssetsManager;
  72497. }());
  72498. BABYLON.AssetsManager = AssetsManager;
  72499. })(BABYLON || (BABYLON = {}));
  72500. //# sourceMappingURL=babylon.assetsManager.js.map
  72501. var BABYLON;
  72502. (function (BABYLON) {
  72503. var serializedGeometries = [];
  72504. var serializeGeometry = function (geometry, serializationGeometries) {
  72505. if (serializedGeometries[geometry.id]) {
  72506. return;
  72507. }
  72508. if (geometry.doNotSerialize) {
  72509. return;
  72510. }
  72511. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  72512. serializationGeometries.boxes.push(geometry.serialize());
  72513. }
  72514. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  72515. serializationGeometries.spheres.push(geometry.serialize());
  72516. }
  72517. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  72518. serializationGeometries.cylinders.push(geometry.serialize());
  72519. }
  72520. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  72521. serializationGeometries.toruses.push(geometry.serialize());
  72522. }
  72523. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  72524. serializationGeometries.grounds.push(geometry.serialize());
  72525. }
  72526. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  72527. serializationGeometries.planes.push(geometry.serialize());
  72528. }
  72529. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  72530. serializationGeometries.torusKnots.push(geometry.serialize());
  72531. }
  72532. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  72533. throw new Error("Unknown primitive type");
  72534. }
  72535. else {
  72536. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  72537. }
  72538. serializedGeometries[geometry.id] = true;
  72539. };
  72540. var serializeMesh = function (mesh, serializationScene) {
  72541. var serializationObject = {};
  72542. // Geometry
  72543. var geometry = mesh._geometry;
  72544. if (geometry) {
  72545. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  72546. // 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
  72547. serializeGeometry(geometry, serializationScene.geometries);
  72548. }
  72549. }
  72550. // Custom
  72551. if (mesh.serialize) {
  72552. mesh.serialize(serializationObject);
  72553. }
  72554. return serializationObject;
  72555. };
  72556. var finalizeSingleMesh = function (mesh, serializationObject) {
  72557. //only works if the mesh is already loaded
  72558. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72559. //serialize material
  72560. if (mesh.material) {
  72561. if (mesh.material instanceof BABYLON.StandardMaterial) {
  72562. serializationObject.materials = serializationObject.materials || [];
  72563. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72564. serializationObject.materials.push(mesh.material.serialize());
  72565. }
  72566. }
  72567. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  72568. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  72569. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72570. serializationObject.multiMaterials.push(mesh.material.serialize());
  72571. }
  72572. }
  72573. }
  72574. //serialize geometry
  72575. var geometry = mesh._geometry;
  72576. if (geometry) {
  72577. if (!serializationObject.geometries) {
  72578. serializationObject.geometries = {};
  72579. serializationObject.geometries.boxes = [];
  72580. serializationObject.geometries.spheres = [];
  72581. serializationObject.geometries.cylinders = [];
  72582. serializationObject.geometries.toruses = [];
  72583. serializationObject.geometries.grounds = [];
  72584. serializationObject.geometries.planes = [];
  72585. serializationObject.geometries.torusKnots = [];
  72586. serializationObject.geometries.vertexData = [];
  72587. }
  72588. serializeGeometry(geometry, serializationObject.geometries);
  72589. }
  72590. // Skeletons
  72591. if (mesh.skeleton) {
  72592. serializationObject.skeletons = serializationObject.skeletons || [];
  72593. serializationObject.skeletons.push(mesh.skeleton.serialize());
  72594. }
  72595. //serialize the actual mesh
  72596. serializationObject.meshes = serializationObject.meshes || [];
  72597. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72598. }
  72599. };
  72600. var SceneSerializer = /** @class */ (function () {
  72601. function SceneSerializer() {
  72602. }
  72603. SceneSerializer.ClearCache = function () {
  72604. serializedGeometries = [];
  72605. };
  72606. SceneSerializer.Serialize = function (scene) {
  72607. var serializationObject = {};
  72608. SceneSerializer.ClearCache();
  72609. // Scene
  72610. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  72611. serializationObject.autoClear = scene.autoClear;
  72612. serializationObject.clearColor = scene.clearColor.asArray();
  72613. serializationObject.ambientColor = scene.ambientColor.asArray();
  72614. serializationObject.gravity = scene.gravity.asArray();
  72615. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  72616. serializationObject.workerCollisions = scene.workerCollisions;
  72617. // Fog
  72618. if (scene.fogMode && scene.fogMode !== 0) {
  72619. serializationObject.fogMode = scene.fogMode;
  72620. serializationObject.fogColor = scene.fogColor.asArray();
  72621. serializationObject.fogStart = scene.fogStart;
  72622. serializationObject.fogEnd = scene.fogEnd;
  72623. serializationObject.fogDensity = scene.fogDensity;
  72624. }
  72625. //Physics
  72626. if (scene.isPhysicsEnabled()) {
  72627. var physicEngine = scene.getPhysicsEngine();
  72628. if (physicEngine) {
  72629. serializationObject.physicsEnabled = true;
  72630. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  72631. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  72632. }
  72633. }
  72634. // Metadata
  72635. if (scene.metadata) {
  72636. serializationObject.metadata = scene.metadata;
  72637. }
  72638. // Morph targets
  72639. serializationObject.morphTargetManagers = [];
  72640. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  72641. var abstractMesh = _a[_i];
  72642. var manager = abstractMesh.morphTargetManager;
  72643. if (manager) {
  72644. serializationObject.morphTargetManagers.push(manager.serialize());
  72645. }
  72646. }
  72647. // Lights
  72648. serializationObject.lights = [];
  72649. var index;
  72650. var light;
  72651. for (index = 0; index < scene.lights.length; index++) {
  72652. light = scene.lights[index];
  72653. if (!light.doNotSerialize) {
  72654. serializationObject.lights.push(light.serialize());
  72655. }
  72656. }
  72657. // Cameras
  72658. serializationObject.cameras = [];
  72659. for (index = 0; index < scene.cameras.length; index++) {
  72660. var camera = scene.cameras[index];
  72661. if (!camera.doNotSerialize) {
  72662. serializationObject.cameras.push(camera.serialize());
  72663. }
  72664. }
  72665. if (scene.activeCamera) {
  72666. serializationObject.activeCameraID = scene.activeCamera.id;
  72667. }
  72668. // Animations
  72669. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  72670. // Materials
  72671. serializationObject.materials = [];
  72672. serializationObject.multiMaterials = [];
  72673. var material;
  72674. for (index = 0; index < scene.materials.length; index++) {
  72675. material = scene.materials[index];
  72676. if (!material.doNotSerialize) {
  72677. serializationObject.materials.push(material.serialize());
  72678. }
  72679. }
  72680. // MultiMaterials
  72681. serializationObject.multiMaterials = [];
  72682. for (index = 0; index < scene.multiMaterials.length; index++) {
  72683. var multiMaterial = scene.multiMaterials[index];
  72684. serializationObject.multiMaterials.push(multiMaterial.serialize());
  72685. }
  72686. // Skeletons
  72687. serializationObject.skeletons = [];
  72688. for (index = 0; index < scene.skeletons.length; index++) {
  72689. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  72690. }
  72691. // Geometries
  72692. serializationObject.geometries = {};
  72693. serializationObject.geometries.boxes = [];
  72694. serializationObject.geometries.spheres = [];
  72695. serializationObject.geometries.cylinders = [];
  72696. serializationObject.geometries.toruses = [];
  72697. serializationObject.geometries.grounds = [];
  72698. serializationObject.geometries.planes = [];
  72699. serializationObject.geometries.torusKnots = [];
  72700. serializationObject.geometries.vertexData = [];
  72701. serializedGeometries = [];
  72702. var geometries = scene.getGeometries();
  72703. for (index = 0; index < geometries.length; index++) {
  72704. var geometry = geometries[index];
  72705. if (geometry.isReady()) {
  72706. serializeGeometry(geometry, serializationObject.geometries);
  72707. }
  72708. }
  72709. // Meshes
  72710. serializationObject.meshes = [];
  72711. for (index = 0; index < scene.meshes.length; index++) {
  72712. var abstractMesh = scene.meshes[index];
  72713. if (abstractMesh instanceof BABYLON.Mesh) {
  72714. var mesh = abstractMesh;
  72715. if (!mesh.doNotSerialize) {
  72716. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72717. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72718. }
  72719. }
  72720. }
  72721. }
  72722. // Particles Systems
  72723. serializationObject.particleSystems = [];
  72724. for (index = 0; index < scene.particleSystems.length; index++) {
  72725. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  72726. }
  72727. // Lens flares
  72728. serializationObject.lensFlareSystems = [];
  72729. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  72730. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  72731. }
  72732. // Shadows
  72733. serializationObject.shadowGenerators = [];
  72734. for (index = 0; index < scene.lights.length; index++) {
  72735. light = scene.lights[index];
  72736. var shadowGenerator = light.getShadowGenerator();
  72737. if (shadowGenerator) {
  72738. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  72739. }
  72740. }
  72741. // Action Manager
  72742. if (scene.actionManager) {
  72743. serializationObject.actions = scene.actionManager.serialize("scene");
  72744. }
  72745. // Audio
  72746. serializationObject.sounds = [];
  72747. for (index = 0; index < scene.soundTracks.length; index++) {
  72748. var soundtrack = scene.soundTracks[index];
  72749. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72750. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72751. }
  72752. }
  72753. return serializationObject;
  72754. };
  72755. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  72756. if (withParents === void 0) { withParents = false; }
  72757. if (withChildren === void 0) { withChildren = false; }
  72758. var serializationObject = {};
  72759. SceneSerializer.ClearCache();
  72760. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  72761. if (withParents || withChildren) {
  72762. //deliberate for loop! not for each, appended should be processed as well.
  72763. for (var i = 0; i < toSerialize.length; ++i) {
  72764. if (withChildren) {
  72765. toSerialize[i].getDescendants().forEach(function (node) {
  72766. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  72767. toSerialize.push(node);
  72768. }
  72769. });
  72770. }
  72771. //make sure the array doesn't contain the object already
  72772. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  72773. toSerialize.push(toSerialize[i].parent);
  72774. }
  72775. }
  72776. }
  72777. toSerialize.forEach(function (mesh) {
  72778. finalizeSingleMesh(mesh, serializationObject);
  72779. });
  72780. return serializationObject;
  72781. };
  72782. return SceneSerializer;
  72783. }());
  72784. BABYLON.SceneSerializer = SceneSerializer;
  72785. })(BABYLON || (BABYLON = {}));
  72786. //# sourceMappingURL=babylon.sceneSerializer.js.map
  72787. var BABYLON;
  72788. (function (BABYLON) {
  72789. var ReflectionProbe = /** @class */ (function () {
  72790. function ReflectionProbe(name, size, scene, generateMipMaps) {
  72791. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72792. var _this = this;
  72793. this.name = name;
  72794. this._viewMatrix = BABYLON.Matrix.Identity();
  72795. this._target = BABYLON.Vector3.Zero();
  72796. this._add = BABYLON.Vector3.Zero();
  72797. this.invertYAxis = false;
  72798. this.position = BABYLON.Vector3.Zero();
  72799. this._scene = scene;
  72800. this._scene.reflectionProbes.push(this);
  72801. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  72802. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  72803. switch (faceIndex) {
  72804. case 0:
  72805. _this._add.copyFromFloats(1, 0, 0);
  72806. break;
  72807. case 1:
  72808. _this._add.copyFromFloats(-1, 0, 0);
  72809. break;
  72810. case 2:
  72811. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  72812. break;
  72813. case 3:
  72814. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  72815. break;
  72816. case 4:
  72817. _this._add.copyFromFloats(0, 0, 1);
  72818. break;
  72819. case 5:
  72820. _this._add.copyFromFloats(0, 0, -1);
  72821. break;
  72822. }
  72823. if (_this._attachedMesh) {
  72824. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  72825. }
  72826. _this.position.addToRef(_this._add, _this._target);
  72827. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  72828. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  72829. });
  72830. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  72831. scene.updateTransformMatrix(true);
  72832. });
  72833. if (scene.activeCamera) {
  72834. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  72835. }
  72836. }
  72837. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  72838. get: function () {
  72839. return this._renderTargetTexture.samples;
  72840. },
  72841. set: function (value) {
  72842. this._renderTargetTexture.samples = value;
  72843. },
  72844. enumerable: true,
  72845. configurable: true
  72846. });
  72847. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  72848. get: function () {
  72849. return this._renderTargetTexture.refreshRate;
  72850. },
  72851. set: function (value) {
  72852. this._renderTargetTexture.refreshRate = value;
  72853. },
  72854. enumerable: true,
  72855. configurable: true
  72856. });
  72857. ReflectionProbe.prototype.getScene = function () {
  72858. return this._scene;
  72859. };
  72860. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  72861. get: function () {
  72862. return this._renderTargetTexture;
  72863. },
  72864. enumerable: true,
  72865. configurable: true
  72866. });
  72867. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  72868. get: function () {
  72869. return this._renderTargetTexture.renderList;
  72870. },
  72871. enumerable: true,
  72872. configurable: true
  72873. });
  72874. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  72875. this._attachedMesh = mesh;
  72876. };
  72877. /**
  72878. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  72879. *
  72880. * @param renderingGroupId The rendering group id corresponding to its index
  72881. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  72882. */
  72883. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  72884. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  72885. };
  72886. ReflectionProbe.prototype.dispose = function () {
  72887. var index = this._scene.reflectionProbes.indexOf(this);
  72888. if (index !== -1) {
  72889. // Remove from the scene if found
  72890. this._scene.reflectionProbes.splice(index, 1);
  72891. }
  72892. if (this._renderTargetTexture) {
  72893. this._renderTargetTexture.dispose();
  72894. this._renderTargetTexture = null;
  72895. }
  72896. };
  72897. return ReflectionProbe;
  72898. }());
  72899. BABYLON.ReflectionProbe = ReflectionProbe;
  72900. })(BABYLON || (BABYLON = {}));
  72901. //# sourceMappingURL=babylon.reflectionProbe.js.map
  72902. var BABYLON;
  72903. (function (BABYLON) {
  72904. var Layer = /** @class */ (function () {
  72905. function Layer(name, imgUrl, scene, isBackground, color) {
  72906. this.name = name;
  72907. this.scale = new BABYLON.Vector2(1, 1);
  72908. this.offset = new BABYLON.Vector2(0, 0);
  72909. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  72910. this.layerMask = 0x0FFFFFFF;
  72911. this._vertexBuffers = {};
  72912. // Events
  72913. /**
  72914. * An event triggered when the layer is disposed.
  72915. * @type {BABYLON.Observable}
  72916. */
  72917. this.onDisposeObservable = new BABYLON.Observable();
  72918. /**
  72919. * An event triggered before rendering the scene
  72920. * @type {BABYLON.Observable}
  72921. */
  72922. this.onBeforeRenderObservable = new BABYLON.Observable();
  72923. /**
  72924. * An event triggered after rendering the scene
  72925. * @type {BABYLON.Observable}
  72926. */
  72927. this.onAfterRenderObservable = new BABYLON.Observable();
  72928. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  72929. this.isBackground = isBackground === undefined ? true : isBackground;
  72930. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  72931. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  72932. this._scene.layers.push(this);
  72933. var engine = this._scene.getEngine();
  72934. // VBO
  72935. var vertices = [];
  72936. vertices.push(1, 1);
  72937. vertices.push(-1, 1);
  72938. vertices.push(-1, -1);
  72939. vertices.push(1, -1);
  72940. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72941. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  72942. this._createIndexBuffer();
  72943. // Effects
  72944. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  72945. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  72946. }
  72947. Object.defineProperty(Layer.prototype, "onDispose", {
  72948. set: function (callback) {
  72949. if (this._onDisposeObserver) {
  72950. this.onDisposeObservable.remove(this._onDisposeObserver);
  72951. }
  72952. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  72953. },
  72954. enumerable: true,
  72955. configurable: true
  72956. });
  72957. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  72958. set: function (callback) {
  72959. if (this._onBeforeRenderObserver) {
  72960. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72961. }
  72962. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72963. },
  72964. enumerable: true,
  72965. configurable: true
  72966. });
  72967. Object.defineProperty(Layer.prototype, "onAfterRender", {
  72968. set: function (callback) {
  72969. if (this._onAfterRenderObserver) {
  72970. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72971. }
  72972. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72973. },
  72974. enumerable: true,
  72975. configurable: true
  72976. });
  72977. Layer.prototype._createIndexBuffer = function () {
  72978. var engine = this._scene.getEngine();
  72979. // Indices
  72980. var indices = [];
  72981. indices.push(0);
  72982. indices.push(1);
  72983. indices.push(2);
  72984. indices.push(0);
  72985. indices.push(2);
  72986. indices.push(3);
  72987. this._indexBuffer = engine.createIndexBuffer(indices);
  72988. };
  72989. Layer.prototype._rebuild = function () {
  72990. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72991. if (vb) {
  72992. vb._rebuild();
  72993. }
  72994. this._createIndexBuffer();
  72995. };
  72996. Layer.prototype.render = function () {
  72997. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  72998. // Check
  72999. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73000. return;
  73001. var engine = this._scene.getEngine();
  73002. this.onBeforeRenderObservable.notifyObservers(this);
  73003. // Render
  73004. engine.enableEffect(currentEffect);
  73005. engine.setState(false);
  73006. // Texture
  73007. currentEffect.setTexture("textureSampler", this.texture);
  73008. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73009. // Color
  73010. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73011. // Scale / offset
  73012. currentEffect.setVector2("offset", this.offset);
  73013. currentEffect.setVector2("scale", this.scale);
  73014. // VBOs
  73015. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73016. // Draw order
  73017. if (!this.alphaTest) {
  73018. engine.setAlphaMode(this.alphaBlendingMode);
  73019. engine.draw(true, 0, 6);
  73020. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73021. }
  73022. else {
  73023. engine.draw(true, 0, 6);
  73024. }
  73025. this.onAfterRenderObservable.notifyObservers(this);
  73026. };
  73027. Layer.prototype.dispose = function () {
  73028. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73029. if (vertexBuffer) {
  73030. vertexBuffer.dispose();
  73031. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73032. }
  73033. if (this._indexBuffer) {
  73034. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73035. this._indexBuffer = null;
  73036. }
  73037. if (this.texture) {
  73038. this.texture.dispose();
  73039. this.texture = null;
  73040. }
  73041. // Remove from scene
  73042. var index = this._scene.layers.indexOf(this);
  73043. this._scene.layers.splice(index, 1);
  73044. // Callback
  73045. this.onDisposeObservable.notifyObservers(this);
  73046. this.onDisposeObservable.clear();
  73047. this.onAfterRenderObservable.clear();
  73048. this.onBeforeRenderObservable.clear();
  73049. };
  73050. return Layer;
  73051. }());
  73052. BABYLON.Layer = Layer;
  73053. })(BABYLON || (BABYLON = {}));
  73054. //# sourceMappingURL=babylon.layer.js.map
  73055. var BABYLON;
  73056. (function (BABYLON) {
  73057. var TextureTools = /** @class */ (function () {
  73058. function TextureTools() {
  73059. }
  73060. /**
  73061. * Uses the GPU to create a copy texture rescaled at a given size
  73062. * @param texture Texture to copy from
  73063. * @param width Desired width
  73064. * @param height Desired height
  73065. * @return Generated texture
  73066. */
  73067. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73068. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73069. var scene = texture.getScene();
  73070. var engine = scene.getEngine();
  73071. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73072. rtt.wrapU = texture.wrapU;
  73073. rtt.wrapV = texture.wrapV;
  73074. rtt.uOffset = texture.uOffset;
  73075. rtt.vOffset = texture.vOffset;
  73076. rtt.uScale = texture.uScale;
  73077. rtt.vScale = texture.vScale;
  73078. rtt.uAng = texture.uAng;
  73079. rtt.vAng = texture.vAng;
  73080. rtt.wAng = texture.wAng;
  73081. rtt.coordinatesIndex = texture.coordinatesIndex;
  73082. rtt.level = texture.level;
  73083. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73084. rtt._texture.isReady = false;
  73085. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73086. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73087. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73088. passPostProcess.getEffect().executeWhenCompiled(function () {
  73089. passPostProcess.onApply = function (effect) {
  73090. effect.setTexture("textureSampler", texture);
  73091. };
  73092. var internalTexture = rtt.getInternalTexture();
  73093. if (internalTexture) {
  73094. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73095. engine.unBindFramebuffer(internalTexture);
  73096. rtt.disposeFramebufferObjects();
  73097. passPostProcess.dispose();
  73098. internalTexture.isReady = true;
  73099. }
  73100. });
  73101. return rtt;
  73102. };
  73103. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73104. if (!scene._environmentBRDFTexture) {
  73105. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73106. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73107. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73108. scene._environmentBRDFTexture = texture;
  73109. }
  73110. return scene._environmentBRDFTexture;
  73111. };
  73112. 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=";
  73113. return TextureTools;
  73114. }());
  73115. BABYLON.TextureTools = TextureTools;
  73116. })(BABYLON || (BABYLON = {}));
  73117. //# sourceMappingURL=babylon.textureTools.js.map
  73118. var BABYLON;
  73119. (function (BABYLON) {
  73120. var FramingBehavior = /** @class */ (function () {
  73121. function FramingBehavior() {
  73122. this._mode = FramingBehavior.FitFrustumSidesMode;
  73123. this._radiusScale = 1.0;
  73124. this._positionScale = 0.5;
  73125. this._defaultElevation = 0.3;
  73126. this._elevationReturnTime = 1500;
  73127. this._elevationReturnWaitTime = 1000;
  73128. this._zoomStopsAnimation = false;
  73129. this._framingTime = 1500;
  73130. this._isPointerDown = false;
  73131. this._lastInteractionTime = -Infinity;
  73132. // Framing control
  73133. this._animatables = new Array();
  73134. this._betaIsAnimating = false;
  73135. }
  73136. Object.defineProperty(FramingBehavior.prototype, "name", {
  73137. get: function () {
  73138. return "Framing";
  73139. },
  73140. enumerable: true,
  73141. configurable: true
  73142. });
  73143. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73144. /**
  73145. * Gets current mode used by the behavior.
  73146. */
  73147. get: function () {
  73148. return this._mode;
  73149. },
  73150. /**
  73151. * Sets the current mode used by the behavior
  73152. */
  73153. set: function (mode) {
  73154. this._mode = mode;
  73155. },
  73156. enumerable: true,
  73157. configurable: true
  73158. });
  73159. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73160. /**
  73161. * Gets the scale applied to the radius
  73162. */
  73163. get: function () {
  73164. return this._radiusScale;
  73165. },
  73166. /**
  73167. * Sets the scale applied to the radius (1 by default)
  73168. */
  73169. set: function (radius) {
  73170. this._radiusScale = radius;
  73171. },
  73172. enumerable: true,
  73173. configurable: true
  73174. });
  73175. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73176. /**
  73177. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73178. */
  73179. get: function () {
  73180. return this._positionScale;
  73181. },
  73182. /**
  73183. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73184. */
  73185. set: function (scale) {
  73186. this._positionScale = scale;
  73187. },
  73188. enumerable: true,
  73189. configurable: true
  73190. });
  73191. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73192. /**
  73193. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73194. * behaviour is triggered, in radians.
  73195. */
  73196. get: function () {
  73197. return this._defaultElevation;
  73198. },
  73199. /**
  73200. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73201. * behaviour is triggered, in radians.
  73202. */
  73203. set: function (elevation) {
  73204. this._defaultElevation = elevation;
  73205. },
  73206. enumerable: true,
  73207. configurable: true
  73208. });
  73209. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73210. /**
  73211. * Gets the time (in milliseconds) taken to return to the default beta position.
  73212. * Negative value indicates camera should not return to default.
  73213. */
  73214. get: function () {
  73215. return this._elevationReturnTime;
  73216. },
  73217. /**
  73218. * Sets the time (in milliseconds) taken to return to the default beta position.
  73219. * Negative value indicates camera should not return to default.
  73220. */
  73221. set: function (speed) {
  73222. this._elevationReturnTime = speed;
  73223. },
  73224. enumerable: true,
  73225. configurable: true
  73226. });
  73227. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73228. /**
  73229. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73230. */
  73231. get: function () {
  73232. return this._elevationReturnWaitTime;
  73233. },
  73234. /**
  73235. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73236. */
  73237. set: function (time) {
  73238. this._elevationReturnWaitTime = time;
  73239. },
  73240. enumerable: true,
  73241. configurable: true
  73242. });
  73243. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73244. /**
  73245. * Gets the flag that indicates if user zooming should stop animation.
  73246. */
  73247. get: function () {
  73248. return this._zoomStopsAnimation;
  73249. },
  73250. /**
  73251. * Sets the flag that indicates if user zooming should stop animation.
  73252. */
  73253. set: function (flag) {
  73254. this._zoomStopsAnimation = flag;
  73255. },
  73256. enumerable: true,
  73257. configurable: true
  73258. });
  73259. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73260. /**
  73261. * Gets the transition time when framing the mesh, in milliseconds
  73262. */
  73263. get: function () {
  73264. return this._framingTime;
  73265. },
  73266. /**
  73267. * Sets the transition time when framing the mesh, in milliseconds
  73268. */
  73269. set: function (time) {
  73270. this._framingTime = time;
  73271. },
  73272. enumerable: true,
  73273. configurable: true
  73274. });
  73275. FramingBehavior.prototype.attach = function (camera) {
  73276. var _this = this;
  73277. this._attachedCamera = camera;
  73278. var scene = this._attachedCamera.getScene();
  73279. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73280. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73281. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73282. _this._isPointerDown = true;
  73283. return;
  73284. }
  73285. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73286. _this._isPointerDown = false;
  73287. }
  73288. });
  73289. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73290. if (mesh) {
  73291. _this.zoomOnMesh(mesh);
  73292. }
  73293. });
  73294. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73295. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73296. _this._applyUserInteraction();
  73297. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73298. // back to the default position after a given timeout
  73299. _this._maintainCameraAboveGround();
  73300. });
  73301. };
  73302. FramingBehavior.prototype.detach = function () {
  73303. if (!this._attachedCamera) {
  73304. return;
  73305. }
  73306. var scene = this._attachedCamera.getScene();
  73307. if (this._onPrePointerObservableObserver) {
  73308. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73309. }
  73310. if (this._onAfterCheckInputsObserver) {
  73311. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73312. }
  73313. if (this._onMeshTargetChangedObserver) {
  73314. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73315. }
  73316. this._attachedCamera = null;
  73317. };
  73318. /**
  73319. * Targets the given mesh and updates zoom level accordingly.
  73320. * @param mesh The mesh to target.
  73321. * @param radius Optional. If a cached radius position already exists, overrides default.
  73322. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73323. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73324. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73325. */
  73326. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73327. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73328. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73329. mesh.computeWorldMatrix(true);
  73330. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73331. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73332. };
  73333. /**
  73334. * Targets the given mesh and updates zoom level accordingly.
  73335. * @param mesh The mesh to target.
  73336. * @param radius Optional. If a cached radius position already exists, overrides default.
  73337. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73338. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73339. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73340. */
  73341. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73342. var _this = this;
  73343. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73344. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73345. var zoomTarget;
  73346. if (!this._attachedCamera) {
  73347. return;
  73348. }
  73349. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73350. var bottom = minimumWorld.y;
  73351. var top = maximumWorld.y;
  73352. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73353. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73354. if (focusOnOriginXZ) {
  73355. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73356. }
  73357. else {
  73358. var centerWorld = minimumWorld.add(radiusWorld);
  73359. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73360. }
  73361. if (!this._vectorTransition) {
  73362. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73363. }
  73364. this._betaIsAnimating = true;
  73365. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73366. if (animatable) {
  73367. this._animatables.push(animatable);
  73368. }
  73369. // sets the radius and lower radius bounds
  73370. // Small delta ensures camera is not always at lower zoom limit.
  73371. var radius = 0;
  73372. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73373. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73374. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73375. radius = position;
  73376. }
  73377. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73378. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73379. if (this._attachedCamera.lowerRadiusLimit === null) {
  73380. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73381. }
  73382. }
  73383. // Set sensibilities
  73384. var extend = maximumWorld.subtract(minimumWorld).length();
  73385. this._attachedCamera.panningSensibility = 5000 / extend;
  73386. this._attachedCamera.wheelPrecision = 100 / radius;
  73387. // transition to new radius
  73388. if (!this._radiusTransition) {
  73389. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73390. }
  73391. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73392. if (onAnimationEnd) {
  73393. onAnimationEnd();
  73394. }
  73395. if (_this._attachedCamera) {
  73396. _this._attachedCamera.storeState();
  73397. }
  73398. });
  73399. if (animatable) {
  73400. this._animatables.push(animatable);
  73401. }
  73402. };
  73403. /**
  73404. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73405. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73406. * frustum width.
  73407. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73408. * to fully enclose the mesh in the viewing frustum.
  73409. */
  73410. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73411. var size = maximumWorld.subtract(minimumWorld);
  73412. var boxVectorGlobalDiagonal = size.length();
  73413. var frustumSlope = this._getFrustumSlope();
  73414. // Formula for setting distance
  73415. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73416. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73417. // Horizon distance
  73418. var radius = radiusWithoutFraming * this._radiusScale;
  73419. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73420. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73421. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73422. var camera = this._attachedCamera;
  73423. if (!camera) {
  73424. return 0;
  73425. }
  73426. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73427. // Don't exceed the requested limit
  73428. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  73429. }
  73430. // Don't exceed the upper radius limit
  73431. if (camera.upperRadiusLimit) {
  73432. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  73433. }
  73434. return distance;
  73435. };
  73436. /**
  73437. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  73438. * is automatically returned to its default position (expected to be above ground plane).
  73439. */
  73440. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  73441. var _this = this;
  73442. if (this._elevationReturnTime < 0) {
  73443. return;
  73444. }
  73445. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  73446. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  73447. var limitBeta = Math.PI * 0.5;
  73448. // Bring the camera back up if below the ground plane
  73449. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  73450. this._betaIsAnimating = true;
  73451. //Transition to new position
  73452. this.stopAllAnimations();
  73453. if (!this._betaTransition) {
  73454. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73455. }
  73456. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  73457. _this._clearAnimationLocks();
  73458. _this.stopAllAnimations();
  73459. });
  73460. if (animatabe) {
  73461. this._animatables.push(animatabe);
  73462. }
  73463. }
  73464. };
  73465. /**
  73466. * Returns the frustum slope based on the canvas ratio and camera FOV
  73467. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  73468. */
  73469. FramingBehavior.prototype._getFrustumSlope = function () {
  73470. // Calculate the viewport ratio
  73471. // Aspect Ratio is Height/Width.
  73472. var camera = this._attachedCamera;
  73473. if (!camera) {
  73474. return BABYLON.Vector2.Zero();
  73475. }
  73476. var engine = camera.getScene().getEngine();
  73477. var aspectRatio = engine.getAspectRatio(camera);
  73478. // Camera FOV is the vertical field of view (top-bottom) in radians.
  73479. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  73480. var frustumSlopeY = Math.tan(camera.fov / 2);
  73481. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  73482. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  73483. // along the forward vector.
  73484. var frustumSlopeX = frustumSlopeY * aspectRatio;
  73485. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  73486. };
  73487. /**
  73488. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  73489. */
  73490. FramingBehavior.prototype._clearAnimationLocks = function () {
  73491. this._betaIsAnimating = false;
  73492. };
  73493. /**
  73494. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73495. */
  73496. FramingBehavior.prototype._applyUserInteraction = function () {
  73497. if (this.isUserIsMoving) {
  73498. this._lastInteractionTime = BABYLON.Tools.Now;
  73499. this.stopAllAnimations();
  73500. this._clearAnimationLocks();
  73501. }
  73502. };
  73503. /**
  73504. * Stops and removes all animations that have been applied to the camera
  73505. */
  73506. FramingBehavior.prototype.stopAllAnimations = function () {
  73507. if (this._attachedCamera) {
  73508. this._attachedCamera.animations = [];
  73509. }
  73510. while (this._animatables.length) {
  73511. if (this._animatables[0]) {
  73512. this._animatables[0].onAnimationEnd = null;
  73513. this._animatables[0].stop();
  73514. }
  73515. this._animatables.shift();
  73516. }
  73517. };
  73518. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  73519. /**
  73520. * Gets a value indicating if the user is moving the camera
  73521. */
  73522. get: function () {
  73523. if (!this._attachedCamera) {
  73524. return false;
  73525. }
  73526. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73527. this._attachedCamera.inertialBetaOffset !== 0 ||
  73528. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73529. this._attachedCamera.inertialPanningX !== 0 ||
  73530. this._attachedCamera.inertialPanningY !== 0 ||
  73531. this._isPointerDown;
  73532. },
  73533. enumerable: true,
  73534. configurable: true
  73535. });
  73536. /**
  73537. * The easing function used by animations
  73538. */
  73539. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  73540. /**
  73541. * The easing mode used by animations
  73542. */
  73543. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  73544. // Statics
  73545. /**
  73546. * The camera can move all the way towards the mesh.
  73547. */
  73548. FramingBehavior.IgnoreBoundsSizeMode = 0;
  73549. /**
  73550. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  73551. */
  73552. FramingBehavior.FitFrustumSidesMode = 1;
  73553. return FramingBehavior;
  73554. }());
  73555. BABYLON.FramingBehavior = FramingBehavior;
  73556. })(BABYLON || (BABYLON = {}));
  73557. //# sourceMappingURL=babylon.framingBehavior.js.map
  73558. var BABYLON;
  73559. (function (BABYLON) {
  73560. /**
  73561. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  73562. */
  73563. var BouncingBehavior = /** @class */ (function () {
  73564. function BouncingBehavior() {
  73565. /**
  73566. * The duration of the animation, in milliseconds
  73567. */
  73568. this.transitionDuration = 450;
  73569. /**
  73570. * Length of the distance animated by the transition when lower radius is reached
  73571. */
  73572. this.lowerRadiusTransitionRange = 2;
  73573. /**
  73574. * Length of the distance animated by the transition when upper radius is reached
  73575. */
  73576. this.upperRadiusTransitionRange = -2;
  73577. this._autoTransitionRange = false;
  73578. // Animations
  73579. this._radiusIsAnimating = false;
  73580. this._radiusBounceTransition = null;
  73581. this._animatables = new Array();
  73582. }
  73583. Object.defineProperty(BouncingBehavior.prototype, "name", {
  73584. get: function () {
  73585. return "Bouncing";
  73586. },
  73587. enumerable: true,
  73588. configurable: true
  73589. });
  73590. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  73591. /**
  73592. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73593. */
  73594. get: function () {
  73595. return this._autoTransitionRange;
  73596. },
  73597. /**
  73598. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73599. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  73600. */
  73601. set: function (value) {
  73602. var _this = this;
  73603. if (this._autoTransitionRange === value) {
  73604. return;
  73605. }
  73606. this._autoTransitionRange = value;
  73607. var camera = this._attachedCamera;
  73608. if (!camera) {
  73609. return;
  73610. }
  73611. if (value) {
  73612. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73613. if (!mesh) {
  73614. return;
  73615. }
  73616. mesh.computeWorldMatrix(true);
  73617. var diagonal = mesh.getBoundingInfo().diagonalLength;
  73618. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  73619. _this.upperRadiusTransitionRange = diagonal * 0.05;
  73620. });
  73621. }
  73622. else if (this._onMeshTargetChangedObserver) {
  73623. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73624. }
  73625. },
  73626. enumerable: true,
  73627. configurable: true
  73628. });
  73629. BouncingBehavior.prototype.attach = function (camera) {
  73630. var _this = this;
  73631. this._attachedCamera = camera;
  73632. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73633. if (!_this._attachedCamera) {
  73634. return;
  73635. }
  73636. // Add the bounce animation to the lower radius limit
  73637. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  73638. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  73639. }
  73640. // Add the bounce animation to the upper radius limit
  73641. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  73642. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  73643. }
  73644. });
  73645. };
  73646. BouncingBehavior.prototype.detach = function () {
  73647. if (!this._attachedCamera) {
  73648. return;
  73649. }
  73650. if (this._onAfterCheckInputsObserver) {
  73651. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73652. }
  73653. if (this._onMeshTargetChangedObserver) {
  73654. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73655. }
  73656. this._attachedCamera = null;
  73657. };
  73658. /**
  73659. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  73660. * @param radiusLimit The limit to check against.
  73661. * @return Bool to indicate if at limit.
  73662. */
  73663. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  73664. if (!this._attachedCamera) {
  73665. return false;
  73666. }
  73667. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  73668. return true;
  73669. }
  73670. return false;
  73671. };
  73672. /**
  73673. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  73674. * @param radiusDelta The delta by which to animate to. Can be negative.
  73675. */
  73676. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  73677. var _this = this;
  73678. if (!this._attachedCamera) {
  73679. return;
  73680. }
  73681. if (!this._radiusBounceTransition) {
  73682. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  73683. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  73684. }
  73685. // Prevent zoom until bounce has completed
  73686. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  73687. this._attachedCamera.wheelPrecision = Infinity;
  73688. this._attachedCamera.inertialRadiusOffset = 0;
  73689. // Animate to the radius limit
  73690. this.stopAllAnimations();
  73691. this._radiusIsAnimating = true;
  73692. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  73693. if (animatable) {
  73694. this._animatables.push(animatable);
  73695. }
  73696. };
  73697. /**
  73698. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  73699. */
  73700. BouncingBehavior.prototype._clearAnimationLocks = function () {
  73701. this._radiusIsAnimating = false;
  73702. if (this._attachedCamera) {
  73703. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  73704. }
  73705. };
  73706. /**
  73707. * Stops and removes all animations that have been applied to the camera
  73708. */
  73709. BouncingBehavior.prototype.stopAllAnimations = function () {
  73710. if (this._attachedCamera) {
  73711. this._attachedCamera.animations = [];
  73712. }
  73713. while (this._animatables.length) {
  73714. this._animatables[0].onAnimationEnd = null;
  73715. this._animatables[0].stop();
  73716. this._animatables.shift();
  73717. }
  73718. };
  73719. /**
  73720. * The easing function used by animations
  73721. */
  73722. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  73723. /**
  73724. * The easing mode used by animations
  73725. */
  73726. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  73727. return BouncingBehavior;
  73728. }());
  73729. BABYLON.BouncingBehavior = BouncingBehavior;
  73730. })(BABYLON || (BABYLON = {}));
  73731. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  73732. var BABYLON;
  73733. (function (BABYLON) {
  73734. var AutoRotationBehavior = /** @class */ (function () {
  73735. function AutoRotationBehavior() {
  73736. this._zoomStopsAnimation = false;
  73737. this._idleRotationSpeed = 0.05;
  73738. this._idleRotationWaitTime = 2000;
  73739. this._idleRotationSpinupTime = 2000;
  73740. this._isPointerDown = false;
  73741. this._lastFrameTime = null;
  73742. this._lastInteractionTime = -Infinity;
  73743. this._cameraRotationSpeed = 0;
  73744. this._lastFrameRadius = 0;
  73745. }
  73746. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  73747. get: function () {
  73748. return "AutoRotation";
  73749. },
  73750. enumerable: true,
  73751. configurable: true
  73752. });
  73753. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  73754. /**
  73755. * Gets the flag that indicates if user zooming should stop animation.
  73756. */
  73757. get: function () {
  73758. return this._zoomStopsAnimation;
  73759. },
  73760. /**
  73761. * Sets the flag that indicates if user zooming should stop animation.
  73762. */
  73763. set: function (flag) {
  73764. this._zoomStopsAnimation = flag;
  73765. },
  73766. enumerable: true,
  73767. configurable: true
  73768. });
  73769. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  73770. /**
  73771. * Gets the default speed at which the camera rotates around the model.
  73772. */
  73773. get: function () {
  73774. return this._idleRotationSpeed;
  73775. },
  73776. /**
  73777. * Sets the default speed at which the camera rotates around the model.
  73778. */
  73779. set: function (speed) {
  73780. this._idleRotationSpeed = speed;
  73781. },
  73782. enumerable: true,
  73783. configurable: true
  73784. });
  73785. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  73786. /**
  73787. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  73788. */
  73789. get: function () {
  73790. return this._idleRotationWaitTime;
  73791. },
  73792. /**
  73793. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  73794. */
  73795. set: function (time) {
  73796. this._idleRotationWaitTime = time;
  73797. },
  73798. enumerable: true,
  73799. configurable: true
  73800. });
  73801. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  73802. /**
  73803. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73804. */
  73805. get: function () {
  73806. return this._idleRotationSpinupTime;
  73807. },
  73808. /**
  73809. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73810. */
  73811. set: function (time) {
  73812. this._idleRotationSpinupTime = time;
  73813. },
  73814. enumerable: true,
  73815. configurable: true
  73816. });
  73817. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  73818. /**
  73819. * Gets a value indicating if the camera is currently rotating because of this behavior
  73820. */
  73821. get: function () {
  73822. return Math.abs(this._cameraRotationSpeed) > 0;
  73823. },
  73824. enumerable: true,
  73825. configurable: true
  73826. });
  73827. AutoRotationBehavior.prototype.attach = function (camera) {
  73828. var _this = this;
  73829. this._attachedCamera = camera;
  73830. var scene = this._attachedCamera.getScene();
  73831. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73832. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73833. _this._isPointerDown = true;
  73834. return;
  73835. }
  73836. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73837. _this._isPointerDown = false;
  73838. }
  73839. });
  73840. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73841. var now = BABYLON.Tools.Now;
  73842. var dt = 0;
  73843. if (_this._lastFrameTime != null) {
  73844. dt = now - _this._lastFrameTime;
  73845. }
  73846. _this._lastFrameTime = now;
  73847. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73848. _this._applyUserInteraction();
  73849. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  73850. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  73851. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  73852. // Step camera rotation by rotation speed
  73853. if (_this._attachedCamera) {
  73854. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  73855. }
  73856. });
  73857. };
  73858. AutoRotationBehavior.prototype.detach = function () {
  73859. if (!this._attachedCamera) {
  73860. return;
  73861. }
  73862. var scene = this._attachedCamera.getScene();
  73863. if (this._onPrePointerObservableObserver) {
  73864. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73865. }
  73866. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73867. this._attachedCamera = null;
  73868. };
  73869. /**
  73870. * Returns true if user is scrolling.
  73871. * @return true if user is scrolling.
  73872. */
  73873. AutoRotationBehavior.prototype._userIsZooming = function () {
  73874. if (!this._attachedCamera) {
  73875. return false;
  73876. }
  73877. return this._attachedCamera.inertialRadiusOffset !== 0;
  73878. };
  73879. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  73880. if (!this._attachedCamera) {
  73881. return false;
  73882. }
  73883. var zoomHasHitLimit = false;
  73884. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  73885. zoomHasHitLimit = true;
  73886. }
  73887. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  73888. this._lastFrameRadius = this._attachedCamera.radius;
  73889. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  73890. };
  73891. /**
  73892. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73893. */
  73894. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  73895. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  73896. this._lastInteractionTime = BABYLON.Tools.Now;
  73897. }
  73898. };
  73899. // Tools
  73900. AutoRotationBehavior.prototype._userIsMoving = function () {
  73901. if (!this._attachedCamera) {
  73902. return false;
  73903. }
  73904. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73905. this._attachedCamera.inertialBetaOffset !== 0 ||
  73906. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73907. this._attachedCamera.inertialPanningX !== 0 ||
  73908. this._attachedCamera.inertialPanningY !== 0 ||
  73909. this._isPointerDown;
  73910. };
  73911. return AutoRotationBehavior;
  73912. }());
  73913. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  73914. })(BABYLON || (BABYLON = {}));
  73915. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  73916. 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(USESPHERICALINFRAGMENT)\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(USESPHERICALINFRAGMENT)\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(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  73917. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#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};"};
  73918. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  73919. var BABYLON;
  73920. (function (BABYLON) {
  73921. var GridMaterialDefines = /** @class */ (function (_super) {
  73922. __extends(GridMaterialDefines, _super);
  73923. function GridMaterialDefines() {
  73924. var _this = _super.call(this) || this;
  73925. _this.TRANSPARENT = false;
  73926. _this.FOG = false;
  73927. _this.PREMULTIPLYALPHA = false;
  73928. _this.rebuild();
  73929. return _this;
  73930. }
  73931. return GridMaterialDefines;
  73932. }(BABYLON.MaterialDefines));
  73933. /**
  73934. * The grid materials allows you to wrap any shape with a grid.
  73935. * Colors are customizable.
  73936. */
  73937. var GridMaterial = /** @class */ (function (_super) {
  73938. __extends(GridMaterial, _super);
  73939. /**
  73940. * constructor
  73941. * @param name The name given to the material in order to identify it afterwards.
  73942. * @param scene The scene the material is used in.
  73943. */
  73944. function GridMaterial(name, scene) {
  73945. var _this = _super.call(this, name, scene) || this;
  73946. /**
  73947. * Main color of the grid (e.g. between lines)
  73948. */
  73949. _this.mainColor = BABYLON.Color3.Black();
  73950. /**
  73951. * Color of the grid lines.
  73952. */
  73953. _this.lineColor = BABYLON.Color3.Teal();
  73954. /**
  73955. * The scale of the grid compared to unit.
  73956. */
  73957. _this.gridRatio = 1.0;
  73958. /**
  73959. * Allows setting an offset for the grid lines.
  73960. */
  73961. _this.gridOffset = BABYLON.Vector3.Zero();
  73962. /**
  73963. * The frequency of thicker lines.
  73964. */
  73965. _this.majorUnitFrequency = 10;
  73966. /**
  73967. * The visibility of minor units in the grid.
  73968. */
  73969. _this.minorUnitVisibility = 0.33;
  73970. /**
  73971. * The grid opacity outside of the lines.
  73972. */
  73973. _this.opacity = 1.0;
  73974. /**
  73975. * Determine RBG output is premultiplied by alpha value.
  73976. */
  73977. _this.preMultiplyAlpha = false;
  73978. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  73979. return _this;
  73980. }
  73981. /**
  73982. * Returns wehter or not the grid requires alpha blending.
  73983. */
  73984. GridMaterial.prototype.needAlphaBlending = function () {
  73985. return this.opacity < 1.0;
  73986. };
  73987. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  73988. if (this.isFrozen) {
  73989. if (this._wasPreviouslyReady && subMesh.effect) {
  73990. return true;
  73991. }
  73992. }
  73993. if (!subMesh._materialDefines) {
  73994. subMesh._materialDefines = new GridMaterialDefines();
  73995. }
  73996. var defines = subMesh._materialDefines;
  73997. var scene = this.getScene();
  73998. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  73999. if (this._renderId === scene.getRenderId()) {
  74000. return true;
  74001. }
  74002. }
  74003. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  74004. defines.TRANSPARENT = !defines.TRANSPARENT;
  74005. defines.markAsUnprocessed();
  74006. }
  74007. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  74008. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  74009. defines.markAsUnprocessed();
  74010. }
  74011. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  74012. // Get correct effect
  74013. if (defines.isDirty) {
  74014. defines.markAsProcessed();
  74015. scene.resetCachedMaterial();
  74016. // Attributes
  74017. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74018. // Defines
  74019. var join = defines.toString();
  74020. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  74021. }
  74022. if (!subMesh.effect || !subMesh.effect.isReady()) {
  74023. return false;
  74024. }
  74025. this._renderId = scene.getRenderId();
  74026. this._wasPreviouslyReady = true;
  74027. return true;
  74028. };
  74029. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  74030. var scene = this.getScene();
  74031. var defines = subMesh._materialDefines;
  74032. if (!defines) {
  74033. return;
  74034. }
  74035. var effect = subMesh.effect;
  74036. if (!effect) {
  74037. return;
  74038. }
  74039. this._activeEffect = effect;
  74040. // Matrices
  74041. this.bindOnlyWorldMatrix(world);
  74042. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  74043. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  74044. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  74045. // Uniforms
  74046. if (this._mustRebind(scene, effect)) {
  74047. this._activeEffect.setColor3("mainColor", this.mainColor);
  74048. this._activeEffect.setColor3("lineColor", this.lineColor);
  74049. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  74050. this._gridControl.x = this.gridRatio;
  74051. this._gridControl.y = Math.round(this.majorUnitFrequency);
  74052. this._gridControl.z = this.minorUnitVisibility;
  74053. this._gridControl.w = this.opacity;
  74054. this._activeEffect.setVector4("gridControl", this._gridControl);
  74055. }
  74056. // Fog
  74057. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  74058. this._afterBind(mesh, this._activeEffect);
  74059. };
  74060. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  74061. _super.prototype.dispose.call(this, forceDisposeEffect);
  74062. };
  74063. GridMaterial.prototype.clone = function (name) {
  74064. var _this = this;
  74065. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  74066. };
  74067. GridMaterial.prototype.serialize = function () {
  74068. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74069. serializationObject.customType = "BABYLON.GridMaterial";
  74070. return serializationObject;
  74071. };
  74072. GridMaterial.prototype.getClassName = function () {
  74073. return "GridMaterial";
  74074. };
  74075. GridMaterial.Parse = function (source, scene, rootUrl) {
  74076. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  74077. };
  74078. __decorate([
  74079. BABYLON.serializeAsColor3()
  74080. ], GridMaterial.prototype, "mainColor", void 0);
  74081. __decorate([
  74082. BABYLON.serializeAsColor3()
  74083. ], GridMaterial.prototype, "lineColor", void 0);
  74084. __decorate([
  74085. BABYLON.serialize()
  74086. ], GridMaterial.prototype, "gridRatio", void 0);
  74087. __decorate([
  74088. BABYLON.serializeAsColor3()
  74089. ], GridMaterial.prototype, "gridOffset", void 0);
  74090. __decorate([
  74091. BABYLON.serialize()
  74092. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  74093. __decorate([
  74094. BABYLON.serialize()
  74095. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  74096. __decorate([
  74097. BABYLON.serialize()
  74098. ], GridMaterial.prototype, "opacity", void 0);
  74099. __decorate([
  74100. BABYLON.serialize()
  74101. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  74102. return GridMaterial;
  74103. }(BABYLON.PushMaterial));
  74104. BABYLON.GridMaterial = GridMaterial;
  74105. })(BABYLON || (BABYLON = {}));
  74106. //# sourceMappingURL=babylon.gridmaterial.js.map
  74107. 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}";
  74108. 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}";
  74109. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74110. var BABYLON;
  74111. (function (BABYLON) {
  74112. /**
  74113. * Background material defines definition.
  74114. */
  74115. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  74116. __extends(BackgroundMaterialDefines, _super);
  74117. /**
  74118. * Constructor of the defines.
  74119. */
  74120. function BackgroundMaterialDefines() {
  74121. var _this = _super.call(this) || this;
  74122. /**
  74123. * True if the opacity texture is in use.
  74124. */
  74125. _this.OPACITY = false;
  74126. /**
  74127. * The direct UV channel to use.
  74128. */
  74129. _this.OPACITYDIRECTUV = 0;
  74130. /**
  74131. * True if the opacity texture is used in gray scale.
  74132. */
  74133. _this.OPACITYRGB = false;
  74134. /**
  74135. * True if the environment texture is in use.
  74136. */
  74137. _this.ENVIRONMENT = false;
  74138. /**
  74139. * True if the environment is defined in gamma space.
  74140. */
  74141. _this.GAMMAENVIRONMENT = false;
  74142. /**
  74143. * True if the environment texture does not contain background dedicated data.
  74144. * The material will fallback to use the luminance of the background.
  74145. */
  74146. _this.RGBENVIRONMENT = false;
  74147. /**
  74148. * True if an extra blur needs to be added in the environment.
  74149. */
  74150. _this.ENVIRONMENTBLUR = false;
  74151. /**
  74152. * False if the current Webgl implementation does not support the texture lod extension.
  74153. */
  74154. _this.TEXTURELODSUPPORT = false;
  74155. /**
  74156. * True if you want the material to fade to the environment color at grazing angle.
  74157. */
  74158. _this.OPACITYFRESNEL = false;
  74159. /**
  74160. * True if you want the shadow being generated from the diffuse color of the light.
  74161. * It is actually using 1 - diffuse to adpat the color to the color not reflected
  74162. * by the target.
  74163. */
  74164. _this.SHADOWFROMLIGHTCOLOR = false;
  74165. // Image Processing Configuration.
  74166. _this.IMAGEPROCESSING = false;
  74167. _this.VIGNETTE = false;
  74168. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  74169. _this.VIGNETTEBLENDMODEOPAQUE = false;
  74170. _this.TONEMAPPING = false;
  74171. _this.CONTRAST = false;
  74172. _this.COLORCURVES = false;
  74173. _this.COLORGRADING = false;
  74174. _this.COLORGRADING3D = false;
  74175. _this.SAMPLER3DGREENDEPTH = false;
  74176. _this.SAMPLER3DBGRMAP = false;
  74177. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  74178. _this.EXPOSURE = false;
  74179. // Default BJS.
  74180. _this.MAINUV1 = false;
  74181. _this.MAINUV2 = false;
  74182. _this.UV1 = false;
  74183. _this.UV2 = false;
  74184. _this.CLIPPLANE = false;
  74185. _this.POINTSIZE = false;
  74186. _this.FOG = false;
  74187. _this.NORMAL = false;
  74188. _this.NUM_BONE_INFLUENCERS = 0;
  74189. _this.BonesPerMesh = 0;
  74190. _this.INSTANCES = false;
  74191. _this.SHADOWFLOAT = false;
  74192. _this.rebuild();
  74193. return _this;
  74194. }
  74195. return BackgroundMaterialDefines;
  74196. }(BABYLON.MaterialDefines));
  74197. /**
  74198. * Background material
  74199. */
  74200. var BackgroundMaterial = /** @class */ (function (_super) {
  74201. __extends(BackgroundMaterial, _super);
  74202. /**
  74203. * constructor
  74204. * @param name The name of the material
  74205. * @param scene The scene to add the material to
  74206. */
  74207. function BackgroundMaterial(name, scene) {
  74208. var _this = _super.call(this, name, scene) || this;
  74209. _this.primaryColor = BABYLON.Color3.White();
  74210. _this.primaryLevel = 1;
  74211. _this.secondaryColor = BABYLON.Color3.Gray();
  74212. _this.secondaryLevel = 1;
  74213. _this.thirdColor = BABYLON.Color3.Black();
  74214. _this.thirdLevel = 1;
  74215. _this.environmentTexture = null;
  74216. _this.opacityTexture = null;
  74217. _this.environmentBlur = 0;
  74218. _this.lightChannelsInTexture = false;
  74219. /**
  74220. * Specify the list of lights casting shadow on the material.
  74221. * All scene shadow lights will be included if null.
  74222. */
  74223. _this._shadowLights = null;
  74224. _this.shadowLights = null;
  74225. _this.shadowBlurScale = 1;
  74226. _this.shadowLevel = 0;
  74227. _this.opacityFresnel = true;
  74228. /**
  74229. * Keep track of the image processing observer to allow dispose and replace.
  74230. */
  74231. _this._imageProcessingObserver = null;
  74232. /**
  74233. * Number of Simultaneous lights allowed on the material.
  74234. */
  74235. _this._maxSimultaneousLights = 4;
  74236. // Temp values kept as cache in the material.
  74237. _this._renderTargets = new BABYLON.SmartArray(16);
  74238. // Setup the default processing configuration to the scene.
  74239. _this._attachImageProcessingConfiguration(null);
  74240. _this.getRenderTargetTextures = function () {
  74241. _this._renderTargets.reset();
  74242. if (_this._opacityTexture && _this._opacityTexture.isRenderTarget) {
  74243. _this._renderTargets.push(_this._opacityTexture);
  74244. }
  74245. if (_this._environmentTexture && _this._environmentTexture.isRenderTarget) {
  74246. _this._renderTargets.push(_this._environmentTexture);
  74247. }
  74248. return _this._renderTargets;
  74249. };
  74250. return _this;
  74251. }
  74252. /**
  74253. * Attaches a new image processing configuration to the PBR Material.
  74254. * @param configuration (if null the scene configuration will be use)
  74255. */
  74256. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  74257. var _this = this;
  74258. if (configuration === this._imageProcessingConfiguration) {
  74259. return;
  74260. }
  74261. // Detaches observer.
  74262. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  74263. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  74264. }
  74265. // Pick the scene configuration if needed.
  74266. if (!configuration) {
  74267. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  74268. }
  74269. else {
  74270. this._imageProcessingConfiguration = configuration;
  74271. }
  74272. // Attaches observer.
  74273. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  74274. _this._markAllSubMeshesAsImageProcessingDirty();
  74275. });
  74276. };
  74277. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  74278. /**
  74279. * Gets the image processing configuration used either in this material.
  74280. */
  74281. get: function () {
  74282. return this._imageProcessingConfiguration;
  74283. },
  74284. /**
  74285. * Sets the Default image processing configuration used either in the this material.
  74286. *
  74287. * If sets to null, the scene one is in use.
  74288. */
  74289. set: function (value) {
  74290. this._attachImageProcessingConfiguration(value);
  74291. // Ensure the effect will be rebuilt.
  74292. this._markAllSubMeshesAsTexturesDirty();
  74293. },
  74294. enumerable: true,
  74295. configurable: true
  74296. });
  74297. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  74298. /**
  74299. * Gets wether the color curves effect is enabled.
  74300. */
  74301. get: function () {
  74302. return this.imageProcessingConfiguration.colorCurvesEnabled;
  74303. },
  74304. /**
  74305. * Sets wether the color curves effect is enabled.
  74306. */
  74307. set: function (value) {
  74308. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  74309. },
  74310. enumerable: true,
  74311. configurable: true
  74312. });
  74313. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  74314. /**
  74315. * Gets wether the color grading effect is enabled.
  74316. */
  74317. get: function () {
  74318. return this.imageProcessingConfiguration.colorGradingEnabled;
  74319. },
  74320. /**
  74321. * Gets wether the color grading effect is enabled.
  74322. */
  74323. set: function (value) {
  74324. this.imageProcessingConfiguration.colorGradingEnabled = value;
  74325. },
  74326. enumerable: true,
  74327. configurable: true
  74328. });
  74329. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  74330. /**
  74331. * Gets wether tonemapping is enabled or not.
  74332. */
  74333. get: function () {
  74334. return this._imageProcessingConfiguration.toneMappingEnabled;
  74335. },
  74336. /**
  74337. * Sets wether tonemapping is enabled or not
  74338. */
  74339. set: function (value) {
  74340. this._imageProcessingConfiguration.toneMappingEnabled = value;
  74341. },
  74342. enumerable: true,
  74343. configurable: true
  74344. });
  74345. ;
  74346. ;
  74347. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  74348. /**
  74349. * The camera exposure used on this material.
  74350. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  74351. * This corresponds to a photographic exposure.
  74352. */
  74353. get: function () {
  74354. return this._imageProcessingConfiguration.exposure;
  74355. },
  74356. /**
  74357. * The camera exposure used on this material.
  74358. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  74359. * This corresponds to a photographic exposure.
  74360. */
  74361. set: function (value) {
  74362. this._imageProcessingConfiguration.exposure = value;
  74363. },
  74364. enumerable: true,
  74365. configurable: true
  74366. });
  74367. ;
  74368. ;
  74369. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  74370. /**
  74371. * Gets The camera contrast used on this material.
  74372. */
  74373. get: function () {
  74374. return this._imageProcessingConfiguration.contrast;
  74375. },
  74376. /**
  74377. * Sets The camera contrast used on this material.
  74378. */
  74379. set: function (value) {
  74380. this._imageProcessingConfiguration.contrast = value;
  74381. },
  74382. enumerable: true,
  74383. configurable: true
  74384. });
  74385. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  74386. /**
  74387. * Gets the Color Grading 2D Lookup Texture.
  74388. */
  74389. get: function () {
  74390. return this._imageProcessingConfiguration.colorGradingTexture;
  74391. },
  74392. /**
  74393. * Sets the Color Grading 2D Lookup Texture.
  74394. */
  74395. set: function (value) {
  74396. this.imageProcessingConfiguration.colorGradingTexture = value;
  74397. },
  74398. enumerable: true,
  74399. configurable: true
  74400. });
  74401. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  74402. /**
  74403. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  74404. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  74405. * 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;
  74406. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  74407. */
  74408. get: function () {
  74409. return this.imageProcessingConfiguration.colorCurves;
  74410. },
  74411. /**
  74412. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  74413. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  74414. * 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;
  74415. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  74416. */
  74417. set: function (value) {
  74418. this.imageProcessingConfiguration.colorCurves = value;
  74419. },
  74420. enumerable: true,
  74421. configurable: true
  74422. });
  74423. /**
  74424. * The entire material has been created in order to prevent overdraw.
  74425. * @returns false
  74426. */
  74427. BackgroundMaterial.prototype.needAlphaTesting = function () {
  74428. return false;
  74429. };
  74430. /**
  74431. * The entire material has been created in order to prevent overdraw.
  74432. * @returns false
  74433. */
  74434. BackgroundMaterial.prototype.needAlphaBlending = function () {
  74435. return false;
  74436. };
  74437. /**
  74438. * Gets the environment texture to use in the material.
  74439. * @returns the texture
  74440. */
  74441. BackgroundMaterial.prototype._getEnvironmentTexture = function () {
  74442. if (this._environmentTexture) {
  74443. return this._environmentTexture;
  74444. }
  74445. return this.getScene().environmentTexture;
  74446. };
  74447. /**
  74448. * Checks wether the material is ready to be rendered for a given mesh.
  74449. * @param mesh The mesh to render
  74450. * @param subMesh The submesh to check against
  74451. * @param useInstances Specify wether or not the material is used with instances
  74452. */
  74453. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74454. var _this = this;
  74455. if (useInstances === void 0) { useInstances = false; }
  74456. if (subMesh.effect && this.isFrozen) {
  74457. if (this._wasPreviouslyReady) {
  74458. return true;
  74459. }
  74460. }
  74461. if (!subMesh._materialDefines) {
  74462. subMesh._materialDefines = new BackgroundMaterialDefines();
  74463. }
  74464. var scene = this.getScene();
  74465. var defines = subMesh._materialDefines;
  74466. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  74467. if (defines._renderId === scene.getRenderId()) {
  74468. return true;
  74469. }
  74470. }
  74471. var engine = scene.getEngine();
  74472. // Lights
  74473. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  74474. defines._needNormals = true;
  74475. // Textures
  74476. if (defines._areTexturesDirty) {
  74477. defines._needUVs = false;
  74478. if (scene.texturesEnabled) {
  74479. if (scene.getEngine().getCaps().textureLOD) {
  74480. defines.TEXTURELODSUPPORT = true;
  74481. }
  74482. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  74483. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  74484. return false;
  74485. }
  74486. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  74487. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  74488. defines.OPACITYFRESNEL = this._opacityFresnel;
  74489. }
  74490. else {
  74491. defines.OPACITY = false;
  74492. defines.OPACITYRGB = false;
  74493. defines.OPACITYFRESNEL = false;
  74494. }
  74495. var environmentTexture = this._getEnvironmentTexture();
  74496. if (environmentTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  74497. if (!environmentTexture.isReadyOrNotBlocking()) {
  74498. return false;
  74499. }
  74500. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(environmentTexture, defines, "ENVIRONMENT");
  74501. defines.GAMMAENVIRONMENT = environmentTexture.gammaSpace;
  74502. defines.ENVIRONMENTBLUR = this._environmentBlur > 0;
  74503. defines.RGBENVIRONMENT = !this.lightChannelsInTexture;
  74504. }
  74505. else {
  74506. defines.ENVIRONMENT = false;
  74507. defines.GAMMAENVIRONMENT = false;
  74508. defines.RGBENVIRONMENT = false;
  74509. }
  74510. }
  74511. }
  74512. if (defines._areImageProcessingDirty) {
  74513. if (!this._imageProcessingConfiguration.isReady()) {
  74514. return false;
  74515. }
  74516. this._imageProcessingConfiguration.prepareDefines(defines);
  74517. }
  74518. // Misc.
  74519. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  74520. // Values that need to be evaluated on every frame
  74521. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  74522. // Attribs
  74523. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  74524. if (mesh) {
  74525. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74526. mesh.createNormals(true);
  74527. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  74528. }
  74529. }
  74530. }
  74531. // Get correct effect
  74532. if (defines.isDirty) {
  74533. defines.markAsProcessed();
  74534. scene.resetCachedMaterial();
  74535. // Fallbacks
  74536. var fallbacks = new BABYLON.EffectFallbacks();
  74537. if (defines.FOG) {
  74538. fallbacks.addFallback(0, "FOG");
  74539. }
  74540. if (defines.POINTSIZE) {
  74541. fallbacks.addFallback(1, "POINTSIZE");
  74542. }
  74543. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  74544. if (defines.NUM_BONE_INFLUENCERS > 0) {
  74545. fallbacks.addCPUSkinningFallback(0, mesh);
  74546. }
  74547. //Attributes
  74548. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74549. if (defines.NORMAL) {
  74550. attribs.push(BABYLON.VertexBuffer.NormalKind);
  74551. }
  74552. if (defines.UV1) {
  74553. attribs.push(BABYLON.VertexBuffer.UVKind);
  74554. }
  74555. if (defines.UV2) {
  74556. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74557. }
  74558. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  74559. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  74560. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  74561. "vFogInfos", "vFogColor", "pointSize",
  74562. "vClipPlane", "mBones",
  74563. "vPrimaryColor", "vSecondaryColor", "vThirdColor",
  74564. "vEnvironmentInfo", "environmentMatrix", "vEnvironmentMicrosurfaceInfos",
  74565. "shadowLevel",
  74566. "vOpacityInfo", "opacityMatrix",
  74567. ];
  74568. var samplers = ["opacitySampler", "environmentSampler", "environmentSamplerLow", "environmentSamplerHigh"];
  74569. var uniformBuffers = ["Material", "Scene"];
  74570. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  74571. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  74572. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  74573. uniformsNames: uniforms,
  74574. uniformBuffersNames: uniformBuffers,
  74575. samplers: samplers,
  74576. defines: defines,
  74577. maxSimultaneousLights: this._maxSimultaneousLights
  74578. });
  74579. var onCompiled = function (effect) {
  74580. if (_this.onCompiled) {
  74581. _this.onCompiled(effect);
  74582. }
  74583. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  74584. };
  74585. var join = defines.toString();
  74586. subMesh.setEffect(scene.getEngine().createEffect("background", {
  74587. attributes: attribs,
  74588. uniformsNames: uniforms,
  74589. uniformBuffersNames: uniformBuffers,
  74590. samplers: samplers,
  74591. defines: join,
  74592. fallbacks: fallbacks,
  74593. onCompiled: onCompiled,
  74594. onError: this.onError,
  74595. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  74596. }, engine), defines);
  74597. this.buildUniformLayout();
  74598. }
  74599. if (!subMesh.effect || !subMesh.effect.isReady()) {
  74600. return false;
  74601. }
  74602. defines._renderId = scene.getRenderId();
  74603. this._wasPreviouslyReady = true;
  74604. return true;
  74605. };
  74606. /**
  74607. * Build the uniform buffer used in the material.
  74608. */
  74609. BackgroundMaterial.prototype.buildUniformLayout = function () {
  74610. // Order is important !
  74611. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  74612. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  74613. this._uniformBuffer.addUniform("vThirdColor", 4);
  74614. this._uniformBuffer.addUniform("vOpacityInfo", 2);
  74615. this._uniformBuffer.addUniform("vEnvironmentInfo", 2);
  74616. this._uniformBuffer.addUniform("opacityMatrix", 16);
  74617. this._uniformBuffer.addUniform("environmentMatrix", 16);
  74618. this._uniformBuffer.addUniform("vEnvironmentMicrosurfaceInfos", 3);
  74619. this._uniformBuffer.addUniform("pointSize", 1);
  74620. this._uniformBuffer.addUniform("shadowLevel", 1);
  74621. this._uniformBuffer.create();
  74622. };
  74623. /**
  74624. * Unbind the material.
  74625. */
  74626. BackgroundMaterial.prototype.unbind = function () {
  74627. if (this._opacityTexture && this._opacityTexture.isRenderTarget) {
  74628. this._uniformBuffer.setTexture("opacitySampler", null);
  74629. }
  74630. if (this._environmentTexture && this._environmentTexture.isRenderTarget) {
  74631. this._uniformBuffer.setTexture("environmentSampler", null);
  74632. }
  74633. _super.prototype.unbind.call(this);
  74634. };
  74635. /**
  74636. * Bind only the world matrix to the material.
  74637. * @param world The world matrix to bind.
  74638. */
  74639. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  74640. this._activeEffect.setMatrix("world", world);
  74641. };
  74642. /**
  74643. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  74644. * @param world The world matrix to bind.
  74645. * @param subMesh The submesh to bind for.
  74646. */
  74647. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  74648. var scene = this.getScene();
  74649. var defines = subMesh._materialDefines;
  74650. if (!defines) {
  74651. return;
  74652. }
  74653. var effect = subMesh.effect;
  74654. if (!effect) {
  74655. return;
  74656. }
  74657. this._activeEffect = effect;
  74658. // Matrices
  74659. this.bindOnlyWorldMatrix(world);
  74660. // Bones
  74661. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  74662. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  74663. if (mustRebind) {
  74664. this._uniformBuffer.bindToEffect(effect, "Material");
  74665. this.bindViewProjection(effect);
  74666. var environmentTexture = this._getEnvironmentTexture();
  74667. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  74668. // Texture uniforms
  74669. if (scene.texturesEnabled) {
  74670. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  74671. this._uniformBuffer.updateFloat2("vOpacityInfo", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  74672. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  74673. }
  74674. if (environmentTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  74675. this._uniformBuffer.updateMatrix("environmentMatrix", environmentTexture.getReflectionTextureMatrix());
  74676. this._uniformBuffer.updateFloat2("vEnvironmentInfo", environmentTexture.level, this._environmentBlur);
  74677. this._uniformBuffer.updateFloat3("vEnvironmentMicrosurfaceInfos", environmentTexture.getSize().width, environmentTexture.lodGenerationScale, environmentTexture.lodGenerationOffset);
  74678. }
  74679. }
  74680. if (this.shadowLevel > 0) {
  74681. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  74682. }
  74683. // Point size
  74684. if (this.pointsCloud) {
  74685. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  74686. }
  74687. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  74688. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  74689. this._uniformBuffer.updateColor4("vThirdColor", this._thirdColor, this._thirdLevel);
  74690. }
  74691. // Textures
  74692. if (scene.texturesEnabled) {
  74693. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  74694. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  74695. }
  74696. if (environmentTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  74697. if (defines.ENVIRONMENTBLUR && defines.TEXTURELODSUPPORT) {
  74698. this._uniformBuffer.setTexture("environmentSampler", environmentTexture);
  74699. }
  74700. else if (!defines.ENVIRONMENTBLUR) {
  74701. this._uniformBuffer.setTexture("environmentSampler", environmentTexture);
  74702. }
  74703. else {
  74704. this._uniformBuffer.setTexture("environmentSampler", environmentTexture._lodTextureMid || environmentTexture);
  74705. this._uniformBuffer.setTexture("environmentSamplerLow", environmentTexture._lodTextureLow || environmentTexture);
  74706. this._uniformBuffer.setTexture("environmentSamplerHigh", environmentTexture._lodTextureHigh || environmentTexture);
  74707. }
  74708. }
  74709. }
  74710. // Clip plane
  74711. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  74712. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  74713. // var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  74714. effect.setFloat3("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z);
  74715. }
  74716. if (mustRebind || !this.isFrozen) {
  74717. if (scene.lightsEnabled) {
  74718. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  74719. }
  74720. // View
  74721. this.bindView(effect);
  74722. // Fog
  74723. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  74724. // image processing
  74725. this._imageProcessingConfiguration.bind(this._activeEffect);
  74726. }
  74727. this._uniformBuffer.update();
  74728. this._afterBind(mesh);
  74729. };
  74730. /**
  74731. * Dispose the material.
  74732. * @forceDisposeEffect Force disposal of the associated effect.
  74733. * @forceDisposeTextures Force disposal of the associated textures.
  74734. */
  74735. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  74736. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  74737. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  74738. if (forceDisposeTextures) {
  74739. if (this.opacityTexture) {
  74740. this.opacityTexture.dispose();
  74741. }
  74742. if (this.environmentTexture) {
  74743. this.environmentTexture.dispose();
  74744. }
  74745. }
  74746. this._renderTargets.dispose();
  74747. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  74748. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  74749. }
  74750. _super.prototype.dispose.call(this, forceDisposeEffect);
  74751. };
  74752. /**
  74753. * Clones the material.
  74754. * @name The cloned name.
  74755. * @returns The cloned material.
  74756. */
  74757. BackgroundMaterial.prototype.clone = function (name) {
  74758. var _this = this;
  74759. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  74760. };
  74761. /**
  74762. * Serializes the current material to its JSON representation.
  74763. * @returns The JSON representation.
  74764. */
  74765. BackgroundMaterial.prototype.serialize = function () {
  74766. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74767. serializationObject.customType = "BABYLON.BackgroundMaterial";
  74768. return serializationObject;
  74769. };
  74770. /**
  74771. * Gets the class name of the material
  74772. * @returns "BackgroundMaterial"
  74773. */
  74774. BackgroundMaterial.prototype.getClassName = function () {
  74775. return "BackgroundMaterial";
  74776. };
  74777. /**
  74778. * Parse a JSON input to create back a background material.
  74779. * @param source
  74780. * @param scene
  74781. * @param rootUrl
  74782. * @returns the instantiated BackgroundMaterial.
  74783. */
  74784. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  74785. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  74786. };
  74787. __decorate([
  74788. BABYLON.serializeAsColor3()
  74789. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  74790. __decorate([
  74791. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  74792. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  74793. __decorate([
  74794. BABYLON.serialize()
  74795. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  74796. __decorate([
  74797. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  74798. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  74799. __decorate([
  74800. BABYLON.serializeAsColor3()
  74801. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  74802. __decorate([
  74803. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  74804. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  74805. __decorate([
  74806. BABYLON.serialize()
  74807. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  74808. __decorate([
  74809. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  74810. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  74811. __decorate([
  74812. BABYLON.serializeAsColor3()
  74813. ], BackgroundMaterial.prototype, "_thirdColor", void 0);
  74814. __decorate([
  74815. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  74816. ], BackgroundMaterial.prototype, "thirdColor", void 0);
  74817. __decorate([
  74818. BABYLON.serialize()
  74819. ], BackgroundMaterial.prototype, "_thirdLevel", void 0);
  74820. __decorate([
  74821. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  74822. ], BackgroundMaterial.prototype, "thirdLevel", void 0);
  74823. __decorate([
  74824. BABYLON.serializeAsTexture()
  74825. ], BackgroundMaterial.prototype, "_environmentTexture", void 0);
  74826. __decorate([
  74827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  74828. ], BackgroundMaterial.prototype, "environmentTexture", void 0);
  74829. __decorate([
  74830. BABYLON.serializeAsTexture()
  74831. ], BackgroundMaterial.prototype, "_opacityTexture", void 0);
  74832. __decorate([
  74833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  74834. ], BackgroundMaterial.prototype, "opacityTexture", void 0);
  74835. __decorate([
  74836. BABYLON.serialize()
  74837. ], BackgroundMaterial.prototype, "_environmentBlur", void 0);
  74838. __decorate([
  74839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  74840. ], BackgroundMaterial.prototype, "environmentBlur", void 0);
  74841. __decorate([
  74842. BABYLON.serialize()
  74843. ], BackgroundMaterial.prototype, "_lightChannelsInTexture", void 0);
  74844. __decorate([
  74845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  74846. ], BackgroundMaterial.prototype, "lightChannelsInTexture", void 0);
  74847. __decorate([
  74848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  74849. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  74850. __decorate([
  74851. BABYLON.serialize()
  74852. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  74853. __decorate([
  74854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  74855. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  74856. __decorate([
  74857. BABYLON.serialize()
  74858. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  74859. __decorate([
  74860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  74861. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  74862. __decorate([
  74863. BABYLON.serialize()
  74864. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  74865. __decorate([
  74866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  74867. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  74868. __decorate([
  74869. BABYLON.serializeAsImageProcessingConfiguration()
  74870. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  74871. return BackgroundMaterial;
  74872. }(BABYLON.PushMaterial));
  74873. BABYLON.BackgroundMaterial = BackgroundMaterial;
  74874. })(BABYLON || (BABYLON = {}));
  74875. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  74876. BABYLON.Effect.ShadersStore['backgroundVertexShader'] = "precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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#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(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfo.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\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";
  74877. BABYLON.Effect.ShadersStore['backgroundPixelShader'] = "#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef 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\n#ifdef ENVIRONMENT\n#define sampleEnvironment(s,c) textureCube(s,c)\nuniform samplerCube environmentSampler;\n#ifdef ENVIRONMENTBLUR\n#ifdef TEXTURELODSUPPORT\n#define sampleEnvironmentLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube environmentSamplerLow;\nuniform samplerCube environmentSamplerHigh;\n#endif\n#endif\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>\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.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ENVIRONMENT\nvec3 environmentColor=vec3(0.,0.,0.);\n\nvec3 environmentCoords=(vPositionW.xyz-vEyePosition.xyz);\n#ifdef INVERTCUBICMAP\nenvironmentCoords.y=1.0-environmentCoords.y;\n#endif\n\nenvironmentCoords=vec3(environmentMatrix*vec4(environmentCoords,0));\n#ifdef ENVIRONMENTBLUR\nfloat environmentLOD=vEnvironmentInfo.y;\n#ifdef TEXTURELODSUPPORT\n\nenvironmentLOD=environmentLOD*log2(vEnvironmentMicrosurfaceInfos.x)*vEnvironmentMicrosurfaceInfos.y+vEnvironmentMicrosurfaceInfos.z;\nenvironmentColor=sampleEnvironmentLod(environmentSampler,environmentCoords,environmentLOD).rgb;\n#else\nfloat lodEnvironmentNormalized=clamp(environmentLOD,0.,1.);\nfloat lodEnvironmentNormalizedDoubled=lodEnvironmentNormalized*2.0;\nvec3 environmentSpecularMid=sampleEnvironment(environmentSampler,environmentCoords).rgb;\nif(lodEnvironmentNormalizedDoubled<1.0){\nenvironmentColor=mix(\nsampleEnvironment(environmentSamplerHigh,environmentCoords).rgb,\nenvironmentSpecularMid,\nlodEnvironmentNormalizedDoubled\n);\n} else {\nenvironmentColor=mix(\nenvironmentSpecularMid,\nsampleEnvironment(environmentSamplerLow,environmentCoords).rgb,\nlodEnvironmentNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nenvironmentColor=sampleEnvironment(environmentSampler,environmentCoords).rgb;\n#endif\n#ifdef GAMMAENVIRONMENT\nenvironmentColor=toLinearSpace(environmentColor.rgb);\n#endif\n\nenvironmentColor*=vEnvironmentInfo.x;\n\n#ifdef OPACITY\nvec3 reflectEnvironmentColor=vec3(0.,0.,0.);\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nfloat environmentMix=getLuminance(opacityMap.rgb);\n#else\nfloat environmentMix=opacityMap.a;\n#endif\nenvironmentMix*=vOpacityInfo.y;\n#ifdef OPACITYFRESNEL\n\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nenvironmentMix*=fadeFactor*fadeFactor;\nshadow=mix(1.,shadow,environmentMix);\n#endif\n\nvec3 viewDir=vPositionW.xyz-vEyePosition.xyz;\nvec3 reflectEnvironmentCoords=reflect(viewDir,normalW);\n#ifdef INVERTCUBICMAP\nreflectEnvironmentCoords.y=1.0-reflectEnvironmentCoords.y;\n#endif\n\nreflectEnvironmentCoords=vec3(environmentMatrix*vec4(reflectEnvironmentCoords,0));\n#ifdef ENVIRONMENTBLUR\n#ifdef TEXTURELODSUPPORT\n\nreflectEnvironmentColor=sampleEnvironmentLod(environmentSampler,reflectEnvironmentCoords,environmentLOD).rgb;\n#else\nvec3 reflectEnvironmentSpecularMid=sampleEnvironment(environmentSampler,reflectEnvironmentCoords).rgb;\nif(lodEnvironmentNormalizedDoubled<1.0){\nreflectEnvironmentColor=mix(\nsampleEnvironment(environmentSamplerHigh,reflectEnvironmentCoords).rgb,\nenvironmentSpecularMid,\nlodEnvironmentNormalizedDoubled\n);\n} else {\nreflectEnvironmentColor=mix(\nenvironmentSpecularMid,\nsampleEnvironment(environmentSamplerLow,reflectEnvironmentCoords).rgb,\nlodEnvironmentNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nreflectEnvironmentColor=sampleEnvironment(environmentSampler,reflectEnvironmentCoords).rgb;\n#endif\n#ifdef GAMMAENVIRONMENT\nreflectEnvironmentColor=toLinearSpace(reflectEnvironmentColor.rgb);\n#endif\n\nreflectEnvironmentColor*=vEnvironmentInfo.x;\n\nenvironmentColor=mix(environmentColor,reflectEnvironmentColor,environmentMix);\n#endif\n#else\nvec3 environmentColor=vec3(1.,1.,1.);\n#endif\n\n#ifdef RGBENVIRONMENT\nenvironmentColor=vec3(1.,1.,1.)*getLuminance(environmentColor);\n#endif\n\nvec3 colorBase=environmentColor.r*vPrimaryColor.rgb*vPrimaryColor.a;\ncolorBase+=environmentColor.g*vSecondaryColor.rgb*vSecondaryColor.a;\ncolorBase+=environmentColor.b*vThirdColor.rgb*vThirdColor.a;\ncolorBase=mix(colorBase*shadowLevel,colorBase,shadow);\nvec4 color=vec4(colorBase,1.0);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n}";
  74878. BABYLON.Effect.IncludesShadersStore['backgroundFragmentDeclaration'] = " uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vThirdColor;\nuniform float shadowLevel;\n#ifdef OPACITY\nuniform vec2 vOpacityInfo;\n#endif\n#ifdef ENVIRONMENT\nuniform vec2 vEnvironmentInfo;\nuniform mat4 environmentMatrix;\nuniform vec3 vEnvironmentMicrosurfaceInfos;\n#endif";
  74879. BABYLON.Effect.IncludesShadersStore['backgroundUboDeclaration'] = "layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vThirdColor;\nuniform vec2 vOpacityInfo;\nuniform vec2 vEnvironmentInfo;\nuniform mat4 opacityMatrix;\nuniform mat4 environmentMatrix;\nuniform vec3 vEnvironmentMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};";
  74880. BABYLON.Effect.IncludesShadersStore['backgroundVertexDeclaration'] = "uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfo;\n#endif\n#ifdef ENVIRONMENT\nuniform vec2 vEnvironmentInfo;\nuniform mat4 environmentMatrix;\nuniform vec3 vEnvionmentMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif";
  74881. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74882. var BABYLON;
  74883. (function (BABYLON) {
  74884. var GLTFLoaderCoordinateSystemMode;
  74885. (function (GLTFLoaderCoordinateSystemMode) {
  74886. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  74887. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  74888. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  74889. // The glTF right-handed data is not transformed in any form and is loaded directly.
  74890. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  74891. // Sets the useRightHandedSystem flag on the scene.
  74892. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  74893. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  74894. var GLTFFileLoader = /** @class */ (function () {
  74895. function GLTFFileLoader() {
  74896. // V2 options
  74897. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  74898. this.name = "gltf";
  74899. this.extensions = {
  74900. ".gltf": { isBinary: false },
  74901. ".glb": { isBinary: true }
  74902. };
  74903. }
  74904. GLTFFileLoader.prototype.dispose = function () {
  74905. if (this._loader) {
  74906. this._loader.dispose();
  74907. this._loader = null;
  74908. }
  74909. };
  74910. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74911. var loaderData = GLTFFileLoader._parse(data, onError);
  74912. if (!loaderData) {
  74913. return;
  74914. }
  74915. if (this.onParsed) {
  74916. this.onParsed(loaderData);
  74917. }
  74918. this._loader = this._getLoader(loaderData, onError);
  74919. if (!this._loader) {
  74920. return;
  74921. }
  74922. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  74923. };
  74924. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  74925. var loaderData = GLTFFileLoader._parse(data, onError);
  74926. if (!loaderData) {
  74927. return;
  74928. }
  74929. if (this.onParsed) {
  74930. this.onParsed(loaderData);
  74931. }
  74932. this._loader = this._getLoader(loaderData, onError);
  74933. if (!this._loader) {
  74934. return;
  74935. }
  74936. return this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  74937. };
  74938. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  74939. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  74940. };
  74941. GLTFFileLoader._parse = function (data, onError) {
  74942. try {
  74943. if (data instanceof ArrayBuffer) {
  74944. return GLTFFileLoader._parseBinary(data, onError);
  74945. }
  74946. return {
  74947. json: JSON.parse(data),
  74948. bin: null
  74949. };
  74950. }
  74951. catch (e) {
  74952. onError(e.message);
  74953. return null;
  74954. }
  74955. };
  74956. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  74957. var loaderVersion = { major: 2, minor: 0 };
  74958. var asset = loaderData.json.asset || {};
  74959. var version = GLTFFileLoader._parseVersion(asset.version);
  74960. if (!version) {
  74961. onError("Invalid version: " + asset.version);
  74962. return null;
  74963. }
  74964. if (asset.minVersion !== undefined) {
  74965. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  74966. if (!minVersion) {
  74967. onError("Invalid minimum version: " + asset.minVersion);
  74968. return null;
  74969. }
  74970. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  74971. onError("Incompatible minimum version: " + asset.minVersion);
  74972. return null;
  74973. }
  74974. }
  74975. var createLoaders = {
  74976. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  74977. 2: GLTFFileLoader.CreateGLTFLoaderV2
  74978. };
  74979. var createLoader = createLoaders[version.major];
  74980. if (!createLoader) {
  74981. onError("Unsupported version: " + asset.version);
  74982. return null;
  74983. }
  74984. return createLoader(this);
  74985. };
  74986. GLTFFileLoader._parseBinary = function (data, onError) {
  74987. var Binary = {
  74988. Magic: 0x46546C67
  74989. };
  74990. var binaryReader = new BinaryReader(data);
  74991. var magic = binaryReader.readUint32();
  74992. if (magic !== Binary.Magic) {
  74993. onError("Unexpected magic: " + magic);
  74994. return null;
  74995. }
  74996. var version = binaryReader.readUint32();
  74997. switch (version) {
  74998. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  74999. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  75000. }
  75001. onError("Unsupported version: " + version);
  75002. return null;
  75003. };
  75004. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  75005. var ContentFormat = {
  75006. JSON: 0
  75007. };
  75008. var length = binaryReader.readUint32();
  75009. if (length != binaryReader.getLength()) {
  75010. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75011. return null;
  75012. }
  75013. var contentLength = binaryReader.readUint32();
  75014. var contentFormat = binaryReader.readUint32();
  75015. var content;
  75016. switch (contentFormat) {
  75017. case ContentFormat.JSON:
  75018. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  75019. break;
  75020. default:
  75021. onError("Unexpected content format: " + contentFormat);
  75022. return null;
  75023. }
  75024. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  75025. var body = binaryReader.readUint8Array(bytesRemaining);
  75026. return {
  75027. json: content,
  75028. bin: body
  75029. };
  75030. };
  75031. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  75032. var ChunkFormat = {
  75033. JSON: 0x4E4F534A,
  75034. BIN: 0x004E4942
  75035. };
  75036. var length = binaryReader.readUint32();
  75037. if (length !== binaryReader.getLength()) {
  75038. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75039. return null;
  75040. }
  75041. // JSON chunk
  75042. var chunkLength = binaryReader.readUint32();
  75043. var chunkFormat = binaryReader.readUint32();
  75044. if (chunkFormat !== ChunkFormat.JSON) {
  75045. onError("First chunk format is not JSON");
  75046. return null;
  75047. }
  75048. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  75049. // Look for BIN chunk
  75050. var bin = null;
  75051. while (binaryReader.getPosition() < binaryReader.getLength()) {
  75052. var chunkLength_1 = binaryReader.readUint32();
  75053. var chunkFormat_1 = binaryReader.readUint32();
  75054. switch (chunkFormat_1) {
  75055. case ChunkFormat.JSON:
  75056. onError("Unexpected JSON chunk");
  75057. return null;
  75058. case ChunkFormat.BIN:
  75059. bin = binaryReader.readUint8Array(chunkLength_1);
  75060. break;
  75061. default:
  75062. // ignore unrecognized chunkFormat
  75063. binaryReader.skipBytes(chunkLength_1);
  75064. break;
  75065. }
  75066. }
  75067. return {
  75068. json: json,
  75069. bin: bin
  75070. };
  75071. };
  75072. GLTFFileLoader._parseVersion = function (version) {
  75073. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  75074. if (!match) {
  75075. return null;
  75076. }
  75077. return {
  75078. major: parseInt(match[1]),
  75079. minor: parseInt(match[2])
  75080. };
  75081. };
  75082. GLTFFileLoader._compareVersion = function (a, b) {
  75083. if (a.major > b.major)
  75084. return 1;
  75085. if (a.major < b.major)
  75086. return -1;
  75087. if (a.minor > b.minor)
  75088. return 1;
  75089. if (a.minor < b.minor)
  75090. return -1;
  75091. return 0;
  75092. };
  75093. GLTFFileLoader._decodeBufferToText = function (buffer) {
  75094. var result = "";
  75095. var length = buffer.byteLength;
  75096. for (var i = 0; i < length; i++) {
  75097. result += String.fromCharCode(buffer[i]);
  75098. }
  75099. return result;
  75100. };
  75101. // V1 options
  75102. GLTFFileLoader.HomogeneousCoordinates = false;
  75103. GLTFFileLoader.IncrementalLoading = true;
  75104. return GLTFFileLoader;
  75105. }());
  75106. BABYLON.GLTFFileLoader = GLTFFileLoader;
  75107. var BinaryReader = /** @class */ (function () {
  75108. function BinaryReader(arrayBuffer) {
  75109. this._arrayBuffer = arrayBuffer;
  75110. this._dataView = new DataView(arrayBuffer);
  75111. this._byteOffset = 0;
  75112. }
  75113. BinaryReader.prototype.getPosition = function () {
  75114. return this._byteOffset;
  75115. };
  75116. BinaryReader.prototype.getLength = function () {
  75117. return this._arrayBuffer.byteLength;
  75118. };
  75119. BinaryReader.prototype.readUint32 = function () {
  75120. var value = this._dataView.getUint32(this._byteOffset, true);
  75121. this._byteOffset += 4;
  75122. return value;
  75123. };
  75124. BinaryReader.prototype.readUint8Array = function (length) {
  75125. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  75126. this._byteOffset += length;
  75127. return value;
  75128. };
  75129. BinaryReader.prototype.skipBytes = function (length) {
  75130. this._byteOffset += length;
  75131. };
  75132. return BinaryReader;
  75133. }());
  75134. if (BABYLON.SceneLoader) {
  75135. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  75136. }
  75137. })(BABYLON || (BABYLON = {}));
  75138. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  75139. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75140. var BABYLON;
  75141. (function (BABYLON) {
  75142. var GLTF1;
  75143. (function (GLTF1) {
  75144. /**
  75145. * Enums
  75146. */
  75147. var EComponentType;
  75148. (function (EComponentType) {
  75149. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  75150. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75151. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  75152. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75153. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  75154. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  75155. var EShaderType;
  75156. (function (EShaderType) {
  75157. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  75158. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  75159. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  75160. var EParameterType;
  75161. (function (EParameterType) {
  75162. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  75163. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75164. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  75165. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75166. EParameterType[EParameterType["INT"] = 5124] = "INT";
  75167. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  75168. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  75169. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  75170. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  75171. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  75172. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  75173. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  75174. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  75175. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  75176. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  75177. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  75178. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  75179. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  75180. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  75181. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  75182. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  75183. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  75184. var ETextureWrapMode;
  75185. (function (ETextureWrapMode) {
  75186. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  75187. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  75188. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  75189. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  75190. var ETextureFilterType;
  75191. (function (ETextureFilterType) {
  75192. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  75193. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  75194. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  75195. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  75196. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  75197. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  75198. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  75199. var ETextureFormat;
  75200. (function (ETextureFormat) {
  75201. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  75202. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  75203. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  75204. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  75205. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  75206. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  75207. var ECullingType;
  75208. (function (ECullingType) {
  75209. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  75210. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  75211. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  75212. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  75213. var EBlendingFunction;
  75214. (function (EBlendingFunction) {
  75215. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  75216. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  75217. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  75218. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  75219. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  75220. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  75221. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  75222. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  75223. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  75224. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  75225. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  75226. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  75227. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  75228. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  75229. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  75230. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  75231. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75232. })(BABYLON || (BABYLON = {}));
  75233. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  75234. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75235. var BABYLON;
  75236. (function (BABYLON) {
  75237. var GLTF1;
  75238. (function (GLTF1) {
  75239. /**
  75240. * Tokenizer. Used for shaders compatibility
  75241. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  75242. */
  75243. var ETokenType;
  75244. (function (ETokenType) {
  75245. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  75246. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  75247. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  75248. })(ETokenType || (ETokenType = {}));
  75249. var Tokenizer = /** @class */ (function () {
  75250. function Tokenizer(toParse) {
  75251. this._pos = 0;
  75252. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  75253. this._toParse = toParse;
  75254. this._maxPos = toParse.length;
  75255. }
  75256. Tokenizer.prototype.getNextToken = function () {
  75257. if (this.isEnd())
  75258. return ETokenType.END_OF_INPUT;
  75259. this.currentString = this.read();
  75260. this.currentToken = ETokenType.UNKNOWN;
  75261. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  75262. this.currentToken = ETokenType.IDENTIFIER;
  75263. this.currentIdentifier = this.currentString;
  75264. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  75265. this.currentIdentifier += this.currentString;
  75266. this.forward();
  75267. }
  75268. }
  75269. return this.currentToken;
  75270. };
  75271. Tokenizer.prototype.peek = function () {
  75272. return this._toParse[this._pos];
  75273. };
  75274. Tokenizer.prototype.read = function () {
  75275. return this._toParse[this._pos++];
  75276. };
  75277. Tokenizer.prototype.forward = function () {
  75278. this._pos++;
  75279. };
  75280. Tokenizer.prototype.isEnd = function () {
  75281. return this._pos >= this._maxPos;
  75282. };
  75283. return Tokenizer;
  75284. }());
  75285. /**
  75286. * Values
  75287. */
  75288. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  75289. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  75290. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  75291. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  75292. /**
  75293. * Parse
  75294. */
  75295. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  75296. for (var buf in parsedBuffers) {
  75297. var parsedBuffer = parsedBuffers[buf];
  75298. gltfRuntime.buffers[buf] = parsedBuffer;
  75299. gltfRuntime.buffersCount++;
  75300. }
  75301. };
  75302. var parseShaders = function (parsedShaders, gltfRuntime) {
  75303. for (var sha in parsedShaders) {
  75304. var parsedShader = parsedShaders[sha];
  75305. gltfRuntime.shaders[sha] = parsedShader;
  75306. gltfRuntime.shaderscount++;
  75307. }
  75308. };
  75309. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  75310. for (var object in parsedObjects) {
  75311. var parsedObject = parsedObjects[object];
  75312. gltfRuntime[runtimeProperty][object] = parsedObject;
  75313. }
  75314. };
  75315. /**
  75316. * Utils
  75317. */
  75318. var normalizeUVs = function (buffer) {
  75319. if (!buffer) {
  75320. return;
  75321. }
  75322. for (var i = 0; i < buffer.length / 2; i++) {
  75323. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  75324. }
  75325. };
  75326. var getAttribute = function (attributeParameter) {
  75327. if (attributeParameter.semantic === "NORMAL") {
  75328. return "normal";
  75329. }
  75330. else if (attributeParameter.semantic === "POSITION") {
  75331. return "position";
  75332. }
  75333. else if (attributeParameter.semantic === "JOINT") {
  75334. return "matricesIndices";
  75335. }
  75336. else if (attributeParameter.semantic === "WEIGHT") {
  75337. return "matricesWeights";
  75338. }
  75339. else if (attributeParameter.semantic === "COLOR") {
  75340. return "color";
  75341. }
  75342. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  75343. var channel = Number(attributeParameter.semantic.split("_")[1]);
  75344. return "uv" + (channel === 0 ? "" : channel + 1);
  75345. }
  75346. return null;
  75347. };
  75348. /**
  75349. * Loads and creates animations
  75350. */
  75351. var loadAnimations = function (gltfRuntime) {
  75352. for (var anim in gltfRuntime.animations) {
  75353. var animation = gltfRuntime.animations[anim];
  75354. if (!animation.channels || !animation.samplers) {
  75355. continue;
  75356. }
  75357. var lastAnimation = null;
  75358. for (var i = 0; i < animation.channels.length; i++) {
  75359. // Get parameters and load buffers
  75360. var channel = animation.channels[i];
  75361. var sampler = animation.samplers[channel.sampler];
  75362. if (!sampler) {
  75363. continue;
  75364. }
  75365. var inputData = null;
  75366. var outputData = null;
  75367. if (animation.parameters) {
  75368. inputData = animation.parameters[sampler.input];
  75369. outputData = animation.parameters[sampler.output];
  75370. }
  75371. else {
  75372. inputData = sampler.input;
  75373. outputData = sampler.output;
  75374. }
  75375. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  75376. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  75377. var targetID = channel.target.id;
  75378. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  75379. if (targetNode === null) {
  75380. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  75381. }
  75382. if (targetNode === null) {
  75383. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  75384. continue;
  75385. }
  75386. var isBone = targetNode instanceof BABYLON.Bone;
  75387. // Get target path (position, rotation or scaling)
  75388. var targetPath = channel.target.path;
  75389. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  75390. if (targetPathIndex !== -1) {
  75391. targetPath = babylonAnimationPaths[targetPathIndex];
  75392. }
  75393. // Determine animation type
  75394. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  75395. if (!isBone) {
  75396. if (targetPath === "rotationQuaternion") {
  75397. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  75398. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  75399. }
  75400. else {
  75401. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  75402. }
  75403. }
  75404. // Create animation and key frames
  75405. var babylonAnimation = null;
  75406. var keys = [];
  75407. var arrayOffset = 0;
  75408. var modifyKey = false;
  75409. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  75410. babylonAnimation = lastAnimation;
  75411. modifyKey = true;
  75412. }
  75413. if (!modifyKey) {
  75414. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  75415. }
  75416. // For each frame
  75417. for (var j = 0; j < bufferInput.length; j++) {
  75418. var value = null;
  75419. if (targetPath === "rotationQuaternion") {
  75420. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  75421. arrayOffset += 4;
  75422. }
  75423. else {
  75424. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  75425. arrayOffset += 3;
  75426. }
  75427. if (isBone) {
  75428. var bone = targetNode;
  75429. var translation = BABYLON.Vector3.Zero();
  75430. var rotationQuaternion = new BABYLON.Quaternion();
  75431. var scaling = BABYLON.Vector3.Zero();
  75432. // Warning on decompose
  75433. var mat = bone.getBaseMatrix();
  75434. if (modifyKey && lastAnimation) {
  75435. mat = lastAnimation.getKeys()[j].value;
  75436. }
  75437. mat.decompose(scaling, rotationQuaternion, translation);
  75438. if (targetPath === "position") {
  75439. translation = value;
  75440. }
  75441. else if (targetPath === "rotationQuaternion") {
  75442. rotationQuaternion = value;
  75443. }
  75444. else {
  75445. scaling = value;
  75446. }
  75447. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  75448. }
  75449. if (!modifyKey) {
  75450. keys.push({
  75451. frame: bufferInput[j],
  75452. value: value
  75453. });
  75454. }
  75455. else if (lastAnimation) {
  75456. lastAnimation.getKeys()[j].value = value;
  75457. }
  75458. }
  75459. // Finish
  75460. if (!modifyKey && babylonAnimation) {
  75461. babylonAnimation.setKeys(keys);
  75462. targetNode.animations.push(babylonAnimation);
  75463. }
  75464. lastAnimation = babylonAnimation;
  75465. gltfRuntime.scene.stopAnimation(targetNode);
  75466. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  75467. }
  75468. }
  75469. };
  75470. /**
  75471. * Returns the bones transformation matrix
  75472. */
  75473. var configureBoneTransformation = function (node) {
  75474. var mat = null;
  75475. if (node.translation || node.rotation || node.scale) {
  75476. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  75477. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  75478. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  75479. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  75480. }
  75481. else {
  75482. mat = BABYLON.Matrix.FromArray(node.matrix);
  75483. }
  75484. return mat;
  75485. };
  75486. /**
  75487. * Returns the parent bone
  75488. */
  75489. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  75490. // Try to find
  75491. for (var i = 0; i < newSkeleton.bones.length; i++) {
  75492. if (newSkeleton.bones[i].name === jointName) {
  75493. return newSkeleton.bones[i];
  75494. }
  75495. }
  75496. // Not found, search in gltf nodes
  75497. var nodes = gltfRuntime.nodes;
  75498. for (var nde in nodes) {
  75499. var node = nodes[nde];
  75500. if (!node.jointName) {
  75501. continue;
  75502. }
  75503. var children = node.children;
  75504. for (var i = 0; i < children.length; i++) {
  75505. var child = gltfRuntime.nodes[children[i]];
  75506. if (!child.jointName) {
  75507. continue;
  75508. }
  75509. if (child.jointName === jointName) {
  75510. var mat = configureBoneTransformation(node);
  75511. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  75512. bone.id = nde;
  75513. return bone;
  75514. }
  75515. }
  75516. }
  75517. return null;
  75518. };
  75519. /**
  75520. * Returns the appropriate root node
  75521. */
  75522. var getNodeToRoot = function (nodesToRoot, id) {
  75523. for (var i = 0; i < nodesToRoot.length; i++) {
  75524. var nodeToRoot = nodesToRoot[i];
  75525. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  75526. var child = nodeToRoot.node.children[j];
  75527. if (child === id) {
  75528. return nodeToRoot.bone;
  75529. }
  75530. }
  75531. }
  75532. return null;
  75533. };
  75534. /**
  75535. * Returns the node with the joint name
  75536. */
  75537. var getJointNode = function (gltfRuntime, jointName) {
  75538. var nodes = gltfRuntime.nodes;
  75539. var node = nodes[jointName];
  75540. if (node) {
  75541. return {
  75542. node: node,
  75543. id: jointName
  75544. };
  75545. }
  75546. for (var nde in nodes) {
  75547. node = nodes[nde];
  75548. if (node.jointName === jointName) {
  75549. return {
  75550. node: node,
  75551. id: nde
  75552. };
  75553. }
  75554. }
  75555. return null;
  75556. };
  75557. /**
  75558. * Checks if a nodes is in joints
  75559. */
  75560. var nodeIsInJoints = function (skins, id) {
  75561. for (var i = 0; i < skins.jointNames.length; i++) {
  75562. if (skins.jointNames[i] === id) {
  75563. return true;
  75564. }
  75565. }
  75566. return false;
  75567. };
  75568. /**
  75569. * Fills the nodes to root for bones and builds hierarchy
  75570. */
  75571. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  75572. // Creates nodes for root
  75573. for (var nde in gltfRuntime.nodes) {
  75574. var node = gltfRuntime.nodes[nde];
  75575. var id = nde;
  75576. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  75577. continue;
  75578. }
  75579. // Create node to root bone
  75580. var mat = configureBoneTransformation(node);
  75581. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  75582. bone.id = id;
  75583. nodesToRoot.push({ bone: bone, node: node, id: id });
  75584. }
  75585. // Parenting
  75586. for (var i = 0; i < nodesToRoot.length; i++) {
  75587. var nodeToRoot = nodesToRoot[i];
  75588. var children = nodeToRoot.node.children;
  75589. for (var j = 0; j < children.length; j++) {
  75590. var child = null;
  75591. for (var k = 0; k < nodesToRoot.length; k++) {
  75592. if (nodesToRoot[k].id === children[j]) {
  75593. child = nodesToRoot[k];
  75594. break;
  75595. }
  75596. }
  75597. if (child) {
  75598. child.bone._parent = nodeToRoot.bone;
  75599. nodeToRoot.bone.children.push(child.bone);
  75600. }
  75601. }
  75602. }
  75603. };
  75604. /**
  75605. * Imports a skeleton
  75606. */
  75607. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  75608. if (!newSkeleton) {
  75609. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  75610. }
  75611. if (!skins.babylonSkeleton) {
  75612. return newSkeleton;
  75613. }
  75614. // Find the root bones
  75615. var nodesToRoot = [];
  75616. var nodesToRootToAdd = [];
  75617. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  75618. newSkeleton.bones = [];
  75619. // Joints
  75620. for (var i = 0; i < skins.jointNames.length; i++) {
  75621. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  75622. if (!jointNode) {
  75623. continue;
  75624. }
  75625. var node = jointNode.node;
  75626. if (!node) {
  75627. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  75628. continue;
  75629. }
  75630. var id = jointNode.id;
  75631. // Optimize, if the bone already exists...
  75632. var existingBone = gltfRuntime.scene.getBoneByID(id);
  75633. if (existingBone) {
  75634. newSkeleton.bones.push(existingBone);
  75635. continue;
  75636. }
  75637. // Search for parent bone
  75638. var foundBone = false;
  75639. var parentBone = null;
  75640. for (var j = 0; j < i; j++) {
  75641. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  75642. if (!jointNode_1) {
  75643. continue;
  75644. }
  75645. var joint = jointNode_1.node;
  75646. if (!joint) {
  75647. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  75648. continue;
  75649. }
  75650. var children = joint.children;
  75651. if (!children) {
  75652. continue;
  75653. }
  75654. foundBone = false;
  75655. for (var k = 0; k < children.length; k++) {
  75656. if (children[k] === id) {
  75657. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  75658. foundBone = true;
  75659. break;
  75660. }
  75661. }
  75662. if (foundBone) {
  75663. break;
  75664. }
  75665. }
  75666. // Create bone
  75667. var mat = configureBoneTransformation(node);
  75668. if (!parentBone && nodesToRoot.length > 0) {
  75669. parentBone = getNodeToRoot(nodesToRoot, id);
  75670. if (parentBone) {
  75671. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  75672. nodesToRootToAdd.push(parentBone);
  75673. }
  75674. }
  75675. }
  75676. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  75677. bone.id = id;
  75678. }
  75679. // Polish
  75680. var bones = newSkeleton.bones;
  75681. newSkeleton.bones = [];
  75682. for (var i = 0; i < skins.jointNames.length; i++) {
  75683. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  75684. if (!jointNode) {
  75685. continue;
  75686. }
  75687. for (var j = 0; j < bones.length; j++) {
  75688. if (bones[j].id === jointNode.id) {
  75689. newSkeleton.bones.push(bones[j]);
  75690. break;
  75691. }
  75692. }
  75693. }
  75694. newSkeleton.prepare();
  75695. // Finish
  75696. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  75697. newSkeleton.bones.push(nodesToRootToAdd[i]);
  75698. }
  75699. return newSkeleton;
  75700. };
  75701. /**
  75702. * Imports a mesh and its geometries
  75703. */
  75704. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  75705. if (!newMesh) {
  75706. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  75707. newMesh.id = id;
  75708. }
  75709. if (!node.babylonNode) {
  75710. return newMesh;
  75711. }
  75712. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  75713. if (!newMesh.material) {
  75714. newMesh.material = multiMat;
  75715. }
  75716. var vertexData = new BABYLON.VertexData();
  75717. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  75718. var verticesStarts = new Array();
  75719. var verticesCounts = new Array();
  75720. var indexStarts = new Array();
  75721. var indexCounts = new Array();
  75722. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  75723. var meshID = meshes[meshIndex];
  75724. var mesh = gltfRuntime.meshes[meshID];
  75725. if (!mesh) {
  75726. continue;
  75727. }
  75728. // Positions, normals and UVs
  75729. for (var i = 0; i < mesh.primitives.length; i++) {
  75730. // Temporary vertex data
  75731. var tempVertexData = new BABYLON.VertexData();
  75732. var primitive = mesh.primitives[i];
  75733. if (primitive.mode !== 4) {
  75734. // continue;
  75735. }
  75736. var attributes = primitive.attributes;
  75737. var accessor = null;
  75738. var buffer = null;
  75739. // Set positions, normal and uvs
  75740. for (var semantic in attributes) {
  75741. // Link accessor and buffer view
  75742. accessor = gltfRuntime.accessors[attributes[semantic]];
  75743. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  75744. if (semantic === "NORMAL") {
  75745. tempVertexData.normals = new Float32Array(buffer.length);
  75746. tempVertexData.normals.set(buffer);
  75747. }
  75748. else if (semantic === "POSITION") {
  75749. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  75750. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  75751. for (var j = 0; j < buffer.length; j += 4) {
  75752. tempVertexData.positions[j] = buffer[j];
  75753. tempVertexData.positions[j + 1] = buffer[j + 1];
  75754. tempVertexData.positions[j + 2] = buffer[j + 2];
  75755. }
  75756. }
  75757. else {
  75758. tempVertexData.positions = new Float32Array(buffer.length);
  75759. tempVertexData.positions.set(buffer);
  75760. }
  75761. verticesCounts.push(tempVertexData.positions.length);
  75762. }
  75763. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  75764. var channel = Number(semantic.split("_")[1]);
  75765. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  75766. var uvs = new Float32Array(buffer.length);
  75767. uvs.set(buffer);
  75768. normalizeUVs(uvs);
  75769. tempVertexData.set(uvs, uvKind);
  75770. }
  75771. else if (semantic === "JOINT") {
  75772. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  75773. tempVertexData.matricesIndices.set(buffer);
  75774. }
  75775. else if (semantic === "WEIGHT") {
  75776. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  75777. tempVertexData.matricesWeights.set(buffer);
  75778. }
  75779. else if (semantic === "COLOR") {
  75780. tempVertexData.colors = new Float32Array(buffer.length);
  75781. tempVertexData.colors.set(buffer);
  75782. }
  75783. }
  75784. // Indices
  75785. accessor = gltfRuntime.accessors[primitive.indices];
  75786. if (accessor) {
  75787. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  75788. tempVertexData.indices = new Int32Array(buffer.length);
  75789. tempVertexData.indices.set(buffer);
  75790. indexCounts.push(tempVertexData.indices.length);
  75791. }
  75792. else {
  75793. // Set indices on the fly
  75794. var indices = [];
  75795. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  75796. indices.push(j);
  75797. }
  75798. tempVertexData.indices = new Int32Array(indices);
  75799. indexCounts.push(tempVertexData.indices.length);
  75800. }
  75801. vertexData.merge(tempVertexData);
  75802. // Sub material
  75803. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  75804. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  75805. // Update vertices start and index start
  75806. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  75807. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  75808. }
  75809. }
  75810. // Apply geometry
  75811. geometry.setAllVerticesData(vertexData, false);
  75812. newMesh.computeWorldMatrix(true);
  75813. // Apply submeshes
  75814. newMesh.subMeshes = [];
  75815. var index = 0;
  75816. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  75817. var meshID = meshes[meshIndex];
  75818. var mesh = gltfRuntime.meshes[meshID];
  75819. if (!mesh) {
  75820. continue;
  75821. }
  75822. for (var i = 0; i < mesh.primitives.length; i++) {
  75823. if (mesh.primitives[i].mode !== 4) {
  75824. //continue;
  75825. }
  75826. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  75827. index++;
  75828. }
  75829. }
  75830. // Finish
  75831. return newMesh;
  75832. };
  75833. /**
  75834. * Configure node transformation from position, rotation and scaling
  75835. */
  75836. var configureNode = function (newNode, position, rotation, scaling) {
  75837. if (newNode.position) {
  75838. newNode.position = position;
  75839. }
  75840. if (newNode.rotationQuaternion || newNode.rotation) {
  75841. newNode.rotationQuaternion = rotation;
  75842. }
  75843. if (newNode.scaling) {
  75844. newNode.scaling = scaling;
  75845. }
  75846. };
  75847. /**
  75848. * Configures node from transformation matrix
  75849. */
  75850. var configureNodeFromMatrix = function (newNode, node, parent) {
  75851. if (node.matrix) {
  75852. var position = new BABYLON.Vector3(0, 0, 0);
  75853. var rotation = new BABYLON.Quaternion();
  75854. var scaling = new BABYLON.Vector3(0, 0, 0);
  75855. var mat = BABYLON.Matrix.FromArray(node.matrix);
  75856. mat.decompose(scaling, rotation, position);
  75857. configureNode(newNode, position, rotation, scaling);
  75858. }
  75859. else if (node.translation && node.rotation && node.scale) {
  75860. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  75861. }
  75862. newNode.computeWorldMatrix(true);
  75863. };
  75864. /**
  75865. * Imports a node
  75866. */
  75867. var importNode = function (gltfRuntime, node, id, parent) {
  75868. var lastNode = null;
  75869. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  75870. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  75871. return null;
  75872. }
  75873. }
  75874. // Meshes
  75875. if (node.skin) {
  75876. if (node.meshes) {
  75877. var skin = gltfRuntime.skins[node.skin];
  75878. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  75879. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  75880. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  75881. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  75882. if (!skin.babylonSkeleton) {
  75883. skin.babylonSkeleton = newMesh.skeleton;
  75884. }
  75885. }
  75886. lastNode = newMesh;
  75887. }
  75888. }
  75889. else if (node.meshes) {
  75890. /**
  75891. * Improve meshes property
  75892. */
  75893. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  75894. lastNode = newMesh;
  75895. }
  75896. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  75897. var light = gltfRuntime.lights[node.light];
  75898. if (light) {
  75899. if (light.type === "ambient") {
  75900. var ambienLight = light[light.type];
  75901. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  75902. hemiLight.name = node.name || "";
  75903. if (ambienLight.color) {
  75904. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  75905. }
  75906. lastNode = hemiLight;
  75907. }
  75908. else if (light.type === "directional") {
  75909. var directionalLight = light[light.type];
  75910. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  75911. dirLight.name = node.name || "";
  75912. if (directionalLight.color) {
  75913. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  75914. }
  75915. lastNode = dirLight;
  75916. }
  75917. else if (light.type === "point") {
  75918. var pointLight = light[light.type];
  75919. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  75920. ptLight.name = node.name || "";
  75921. if (pointLight.color) {
  75922. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  75923. }
  75924. lastNode = ptLight;
  75925. }
  75926. else if (light.type === "spot") {
  75927. var spotLight = light[light.type];
  75928. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  75929. spLight.name = node.name || "";
  75930. if (spotLight.color) {
  75931. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  75932. }
  75933. if (spotLight.fallOfAngle) {
  75934. spLight.angle = spotLight.fallOfAngle;
  75935. }
  75936. if (spotLight.fallOffExponent) {
  75937. spLight.exponent = spotLight.fallOffExponent;
  75938. }
  75939. lastNode = spLight;
  75940. }
  75941. }
  75942. }
  75943. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  75944. var camera = gltfRuntime.cameras[node.camera];
  75945. if (camera) {
  75946. if (camera.type === "orthographic") {
  75947. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  75948. orthoCamera.name = node.name || "";
  75949. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  75950. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  75951. lastNode = orthoCamera;
  75952. }
  75953. else if (camera.type === "perspective") {
  75954. var perspectiveCamera = camera[camera.type];
  75955. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  75956. persCamera.name = node.name || "";
  75957. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  75958. if (!perspectiveCamera.aspectRatio) {
  75959. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  75960. }
  75961. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  75962. persCamera.maxZ = perspectiveCamera.zfar;
  75963. persCamera.minZ = perspectiveCamera.znear;
  75964. }
  75965. lastNode = persCamera;
  75966. }
  75967. }
  75968. }
  75969. // Empty node
  75970. if (!node.jointName) {
  75971. if (node.babylonNode) {
  75972. return node.babylonNode;
  75973. }
  75974. else if (lastNode === null) {
  75975. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  75976. node.babylonNode = dummy;
  75977. lastNode = dummy;
  75978. }
  75979. }
  75980. if (lastNode !== null) {
  75981. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  75982. configureNodeFromMatrix(lastNode, node, parent);
  75983. }
  75984. else {
  75985. var translation = node.translation || [0, 0, 0];
  75986. var rotation = node.rotation || [0, 0, 0, 1];
  75987. var scale = node.scale || [1, 1, 1];
  75988. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  75989. }
  75990. lastNode.updateCache(true);
  75991. node.babylonNode = lastNode;
  75992. }
  75993. return lastNode;
  75994. };
  75995. /**
  75996. * Traverses nodes and creates them
  75997. */
  75998. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  75999. if (meshIncluded === void 0) { meshIncluded = false; }
  76000. var node = gltfRuntime.nodes[id];
  76001. var newNode = null;
  76002. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  76003. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  76004. meshIncluded = true;
  76005. }
  76006. else {
  76007. meshIncluded = false;
  76008. }
  76009. }
  76010. else {
  76011. meshIncluded = true;
  76012. }
  76013. if (!node.jointName && meshIncluded) {
  76014. newNode = importNode(gltfRuntime, node, id, parent);
  76015. if (newNode !== null) {
  76016. newNode.id = id;
  76017. newNode.parent = parent;
  76018. }
  76019. }
  76020. if (node.children) {
  76021. for (var i = 0; i < node.children.length; i++) {
  76022. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  76023. }
  76024. }
  76025. };
  76026. /**
  76027. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  76028. */
  76029. var postLoad = function (gltfRuntime) {
  76030. // Nodes
  76031. var currentScene = gltfRuntime.currentScene;
  76032. if (currentScene) {
  76033. for (var i = 0; i < currentScene.nodes.length; i++) {
  76034. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76035. }
  76036. }
  76037. else {
  76038. for (var thing in gltfRuntime.scenes) {
  76039. currentScene = gltfRuntime.scenes[thing];
  76040. for (var i = 0; i < currentScene.nodes.length; i++) {
  76041. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76042. }
  76043. }
  76044. }
  76045. // Set animations
  76046. loadAnimations(gltfRuntime);
  76047. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  76048. var skeleton = gltfRuntime.scene.skeletons[i];
  76049. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  76050. }
  76051. };
  76052. /**
  76053. * onBind shaderrs callback to set uniforms and matrices
  76054. */
  76055. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  76056. var materialValues = material.values || technique.parameters;
  76057. for (var unif in unTreatedUniforms) {
  76058. var uniform = unTreatedUniforms[unif];
  76059. var type = uniform.type;
  76060. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  76061. if (uniform.semantic && !uniform.source && !uniform.node) {
  76062. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  76063. }
  76064. else if (uniform.semantic && (uniform.source || uniform.node)) {
  76065. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  76066. if (source === null) {
  76067. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  76068. }
  76069. if (source === null) {
  76070. continue;
  76071. }
  76072. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  76073. }
  76074. }
  76075. else {
  76076. var value = materialValues[technique.uniforms[unif]];
  76077. if (!value) {
  76078. continue;
  76079. }
  76080. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  76081. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  76082. if (texture === null || texture === undefined) {
  76083. continue;
  76084. }
  76085. shaderMaterial.getEffect().setTexture(unif, texture);
  76086. }
  76087. else {
  76088. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  76089. }
  76090. }
  76091. }
  76092. onSuccess(shaderMaterial);
  76093. };
  76094. /**
  76095. * Prepare uniforms to send the only one time
  76096. * Loads the appropriate textures
  76097. */
  76098. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  76099. var materialValues = material.values || technique.parameters;
  76100. var techniqueUniforms = technique.uniforms;
  76101. /**
  76102. * Prepare values here (not matrices)
  76103. */
  76104. for (var unif in unTreatedUniforms) {
  76105. var uniform = unTreatedUniforms[unif];
  76106. var type = uniform.type;
  76107. var value = materialValues[techniqueUniforms[unif]];
  76108. if (value === undefined) {
  76109. // In case the value is the same for all materials
  76110. value = uniform.value;
  76111. }
  76112. if (!value) {
  76113. continue;
  76114. }
  76115. var onLoadTexture = function (uniformName) {
  76116. return function (texture) {
  76117. if (uniform.value && uniformName) {
  76118. // Static uniform
  76119. shaderMaterial.setTexture(uniformName, texture);
  76120. delete unTreatedUniforms[uniformName];
  76121. }
  76122. };
  76123. };
  76124. // Texture (sampler2D)
  76125. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  76126. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  76127. }
  76128. else {
  76129. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  76130. // Static uniform
  76131. delete unTreatedUniforms[unif];
  76132. }
  76133. }
  76134. }
  76135. };
  76136. /**
  76137. * Shader compilation failed
  76138. */
  76139. var onShaderCompileError = function (program, shaderMaterial, onError) {
  76140. return function (effect, error) {
  76141. shaderMaterial.dispose(true);
  76142. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  76143. };
  76144. };
  76145. /**
  76146. * Shader compilation success
  76147. */
  76148. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  76149. return function (_) {
  76150. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  76151. shaderMaterial.onBind = function (mesh) {
  76152. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  76153. };
  76154. };
  76155. };
  76156. /**
  76157. * Returns the appropriate uniform if already handled by babylon
  76158. */
  76159. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  76160. for (var unif in technique.uniforms) {
  76161. var uniform = technique.uniforms[unif];
  76162. var uniformParameter = technique.parameters[uniform];
  76163. if (tokenizer.currentIdentifier === unif) {
  76164. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  76165. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  76166. if (transformIndex !== -1) {
  76167. delete unTreatedUniforms[unif];
  76168. return babylonTransforms[transformIndex];
  76169. }
  76170. }
  76171. }
  76172. }
  76173. return tokenizer.currentIdentifier;
  76174. };
  76175. /**
  76176. * All shaders loaded. Create materials one by one
  76177. */
  76178. var importMaterials = function (gltfRuntime) {
  76179. // Create materials
  76180. for (var mat in gltfRuntime.materials) {
  76181. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  76182. }
  76183. };
  76184. /**
  76185. * Implementation of the base glTF spec
  76186. */
  76187. var GLTFLoaderBase = /** @class */ (function () {
  76188. function GLTFLoaderBase() {
  76189. }
  76190. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  76191. var gltfRuntime = {
  76192. extensions: {},
  76193. accessors: {},
  76194. buffers: {},
  76195. bufferViews: {},
  76196. meshes: {},
  76197. lights: {},
  76198. cameras: {},
  76199. nodes: {},
  76200. images: {},
  76201. textures: {},
  76202. shaders: {},
  76203. programs: {},
  76204. samplers: {},
  76205. techniques: {},
  76206. materials: {},
  76207. animations: {},
  76208. skins: {},
  76209. extensionsUsed: [],
  76210. scenes: {},
  76211. buffersCount: 0,
  76212. shaderscount: 0,
  76213. scene: scene,
  76214. rootUrl: rootUrl,
  76215. loadedBufferCount: 0,
  76216. loadedBufferViews: {},
  76217. loadedShaderCount: 0,
  76218. importOnlyMeshes: false,
  76219. dummyNodes: []
  76220. };
  76221. // Parse
  76222. if (parsedData.extensions) {
  76223. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  76224. }
  76225. if (parsedData.extensionsUsed) {
  76226. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  76227. }
  76228. if (parsedData.buffers) {
  76229. parseBuffers(parsedData.buffers, gltfRuntime);
  76230. }
  76231. if (parsedData.bufferViews) {
  76232. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  76233. }
  76234. if (parsedData.accessors) {
  76235. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  76236. }
  76237. if (parsedData.meshes) {
  76238. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  76239. }
  76240. if (parsedData.lights) {
  76241. parseObject(parsedData.lights, "lights", gltfRuntime);
  76242. }
  76243. if (parsedData.cameras) {
  76244. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  76245. }
  76246. if (parsedData.nodes) {
  76247. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  76248. }
  76249. if (parsedData.images) {
  76250. parseObject(parsedData.images, "images", gltfRuntime);
  76251. }
  76252. if (parsedData.textures) {
  76253. parseObject(parsedData.textures, "textures", gltfRuntime);
  76254. }
  76255. if (parsedData.shaders) {
  76256. parseShaders(parsedData.shaders, gltfRuntime);
  76257. }
  76258. if (parsedData.programs) {
  76259. parseObject(parsedData.programs, "programs", gltfRuntime);
  76260. }
  76261. if (parsedData.samplers) {
  76262. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  76263. }
  76264. if (parsedData.techniques) {
  76265. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  76266. }
  76267. if (parsedData.materials) {
  76268. parseObject(parsedData.materials, "materials", gltfRuntime);
  76269. }
  76270. if (parsedData.animations) {
  76271. parseObject(parsedData.animations, "animations", gltfRuntime);
  76272. }
  76273. if (parsedData.skins) {
  76274. parseObject(parsedData.skins, "skins", gltfRuntime);
  76275. }
  76276. if (parsedData.scenes) {
  76277. gltfRuntime.scenes = parsedData.scenes;
  76278. }
  76279. if (parsedData.scene && parsedData.scenes) {
  76280. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  76281. }
  76282. return gltfRuntime;
  76283. };
  76284. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  76285. var buffer = gltfRuntime.buffers[id];
  76286. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  76287. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  76288. }
  76289. else {
  76290. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  76291. if (request) {
  76292. onError(request.status + " " + request.statusText);
  76293. }
  76294. });
  76295. }
  76296. };
  76297. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  76298. var texture = gltfRuntime.textures[id];
  76299. if (!texture || !texture.source) {
  76300. onError("");
  76301. return;
  76302. }
  76303. if (texture.babylonTexture) {
  76304. onSuccess(null);
  76305. return;
  76306. }
  76307. var source = gltfRuntime.images[texture.source];
  76308. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  76309. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  76310. }
  76311. else {
  76312. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  76313. if (request) {
  76314. onError(request.status + " " + request.statusText);
  76315. }
  76316. });
  76317. }
  76318. };
  76319. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  76320. var texture = gltfRuntime.textures[id];
  76321. if (texture.babylonTexture) {
  76322. onSuccess(texture.babylonTexture);
  76323. return;
  76324. }
  76325. var sampler = gltfRuntime.samplers[texture.sampler];
  76326. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  76327. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  76328. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  76329. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  76330. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  76331. var blob = new Blob([buffer]);
  76332. var blobURL = URL.createObjectURL(blob);
  76333. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  76334. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  76335. if (sampler.wrapS !== undefined) {
  76336. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  76337. }
  76338. if (sampler.wrapT !== undefined) {
  76339. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  76340. }
  76341. newTexture.name = id;
  76342. texture.babylonTexture = newTexture;
  76343. onSuccess(newTexture);
  76344. };
  76345. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  76346. var shader = gltfRuntime.shaders[id];
  76347. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  76348. var shaderString = atob(shader.uri.split(",")[1]);
  76349. onSuccess(shaderString);
  76350. }
  76351. else {
  76352. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  76353. if (request) {
  76354. onError(request.status + " " + request.statusText);
  76355. }
  76356. });
  76357. }
  76358. };
  76359. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  76360. var material = gltfRuntime.materials[id];
  76361. if (!material.technique) {
  76362. if (onError) {
  76363. onError("No technique found.");
  76364. }
  76365. return;
  76366. }
  76367. var technique = gltfRuntime.techniques[material.technique];
  76368. if (!technique) {
  76369. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  76370. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  76371. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76372. onSuccess(defaultMaterial);
  76373. return;
  76374. }
  76375. var program = gltfRuntime.programs[technique.program];
  76376. var states = technique.states;
  76377. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  76378. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  76379. var newVertexShader = "";
  76380. var newPixelShader = "";
  76381. var vertexTokenizer = new Tokenizer(vertexShader);
  76382. var pixelTokenizer = new Tokenizer(pixelShader);
  76383. var unTreatedUniforms = {};
  76384. var uniforms = [];
  76385. var attributes = [];
  76386. var samplers = [];
  76387. // Fill uniform, sampler2D and attributes
  76388. for (var unif in technique.uniforms) {
  76389. var uniform = technique.uniforms[unif];
  76390. var uniformParameter = technique.parameters[uniform];
  76391. unTreatedUniforms[unif] = uniformParameter;
  76392. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  76393. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  76394. if (transformIndex !== -1) {
  76395. uniforms.push(babylonTransforms[transformIndex]);
  76396. delete unTreatedUniforms[unif];
  76397. }
  76398. else {
  76399. uniforms.push(unif);
  76400. }
  76401. }
  76402. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  76403. samplers.push(unif);
  76404. }
  76405. else {
  76406. uniforms.push(unif);
  76407. }
  76408. }
  76409. for (var attr in technique.attributes) {
  76410. var attribute = technique.attributes[attr];
  76411. var attributeParameter = technique.parameters[attribute];
  76412. if (attributeParameter.semantic) {
  76413. attributes.push(getAttribute(attributeParameter));
  76414. }
  76415. }
  76416. // Configure vertex shader
  76417. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  76418. var tokenType = vertexTokenizer.currentToken;
  76419. if (tokenType !== ETokenType.IDENTIFIER) {
  76420. newVertexShader += vertexTokenizer.currentString;
  76421. continue;
  76422. }
  76423. var foundAttribute = false;
  76424. for (var attr in technique.attributes) {
  76425. var attribute = technique.attributes[attr];
  76426. var attributeParameter = technique.parameters[attribute];
  76427. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  76428. newVertexShader += getAttribute(attributeParameter);
  76429. foundAttribute = true;
  76430. break;
  76431. }
  76432. }
  76433. if (foundAttribute) {
  76434. continue;
  76435. }
  76436. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  76437. }
  76438. // Configure pixel shader
  76439. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  76440. var tokenType = pixelTokenizer.currentToken;
  76441. if (tokenType !== ETokenType.IDENTIFIER) {
  76442. newPixelShader += pixelTokenizer.currentString;
  76443. continue;
  76444. }
  76445. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  76446. }
  76447. // Create shader material
  76448. var shaderPath = {
  76449. vertex: program.vertexShader + id,
  76450. fragment: program.fragmentShader + id
  76451. };
  76452. var options = {
  76453. attributes: attributes,
  76454. uniforms: uniforms,
  76455. samplers: samplers,
  76456. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  76457. };
  76458. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  76459. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  76460. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  76461. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  76462. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  76463. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76464. if (states && states.functions) {
  76465. var functions = states.functions;
  76466. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  76467. shaderMaterial.backFaceCulling = false;
  76468. }
  76469. var blendFunc = functions.blendFuncSeparate;
  76470. if (blendFunc) {
  76471. 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) {
  76472. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  76473. }
  76474. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  76475. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76476. }
  76477. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  76478. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  76479. }
  76480. 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) {
  76481. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  76482. }
  76483. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  76484. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  76485. }
  76486. 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) {
  76487. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  76488. }
  76489. }
  76490. }
  76491. };
  76492. return GLTFLoaderBase;
  76493. }());
  76494. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  76495. /**
  76496. * glTF V1 Loader
  76497. */
  76498. var GLTFLoader = /** @class */ (function () {
  76499. function GLTFLoader() {
  76500. }
  76501. GLTFLoader.RegisterExtension = function (extension) {
  76502. if (GLTFLoader.Extensions[extension.name]) {
  76503. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  76504. return;
  76505. }
  76506. GLTFLoader.Extensions[extension.name] = extension;
  76507. };
  76508. GLTFLoader.prototype.dispose = function () {
  76509. // do nothing
  76510. };
  76511. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  76512. var _this = this;
  76513. scene.useRightHandedSystem = true;
  76514. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  76515. gltfRuntime.importOnlyMeshes = true;
  76516. if (meshesNames === "") {
  76517. gltfRuntime.importMeshesNames = [];
  76518. }
  76519. else if (typeof meshesNames === "string") {
  76520. gltfRuntime.importMeshesNames = [meshesNames];
  76521. }
  76522. else if (meshesNames && !(meshesNames instanceof Array)) {
  76523. gltfRuntime.importMeshesNames = [meshesNames];
  76524. }
  76525. else {
  76526. gltfRuntime.importMeshesNames = [];
  76527. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  76528. }
  76529. // Create nodes
  76530. _this._createNodes(gltfRuntime);
  76531. var meshes = new Array();
  76532. var skeletons = new Array();
  76533. // Fill arrays of meshes and skeletons
  76534. for (var nde in gltfRuntime.nodes) {
  76535. var node = gltfRuntime.nodes[nde];
  76536. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  76537. meshes.push(node.babylonNode);
  76538. }
  76539. }
  76540. for (var skl in gltfRuntime.skins) {
  76541. var skin = gltfRuntime.skins[skl];
  76542. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  76543. skeletons.push(skin.babylonSkeleton);
  76544. }
  76545. }
  76546. // Load buffers, shaders, materials, etc.
  76547. _this._loadBuffersAsync(gltfRuntime, function () {
  76548. _this._loadShadersAsync(gltfRuntime, function () {
  76549. importMaterials(gltfRuntime);
  76550. postLoad(gltfRuntime);
  76551. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  76552. onSuccess(meshes, null, skeletons);
  76553. }
  76554. });
  76555. }, onProgress);
  76556. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  76557. onSuccess(meshes, null, skeletons);
  76558. }
  76559. }, onError);
  76560. return true;
  76561. };
  76562. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  76563. var _this = this;
  76564. scene.useRightHandedSystem = true;
  76565. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  76566. // Load runtime extensios
  76567. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  76568. // Create nodes
  76569. _this._createNodes(gltfRuntime);
  76570. // Load buffers, shaders, materials, etc.
  76571. _this._loadBuffersAsync(gltfRuntime, function () {
  76572. _this._loadShadersAsync(gltfRuntime, function () {
  76573. importMaterials(gltfRuntime);
  76574. postLoad(gltfRuntime);
  76575. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  76576. onSuccess();
  76577. }
  76578. });
  76579. });
  76580. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  76581. onSuccess();
  76582. }
  76583. }, onError);
  76584. }, onError);
  76585. };
  76586. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  76587. var hasShaders = false;
  76588. var processShader = function (sha, shader) {
  76589. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  76590. gltfRuntime.loadedShaderCount++;
  76591. if (shaderString) {
  76592. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  76593. }
  76594. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  76595. onload();
  76596. }
  76597. }, function () {
  76598. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  76599. });
  76600. };
  76601. for (var sha in gltfRuntime.shaders) {
  76602. hasShaders = true;
  76603. var shader = gltfRuntime.shaders[sha];
  76604. if (shader) {
  76605. processShader.bind(this, sha, shader)();
  76606. }
  76607. else {
  76608. BABYLON.Tools.Error("No shader named: " + sha);
  76609. }
  76610. }
  76611. if (!hasShaders) {
  76612. onload();
  76613. }
  76614. };
  76615. ;
  76616. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  76617. var hasBuffers = false;
  76618. var processBuffer = function (buf, buffer) {
  76619. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  76620. gltfRuntime.loadedBufferCount++;
  76621. if (bufferView) {
  76622. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  76623. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  76624. }
  76625. gltfRuntime.loadedBufferViews[buf] = bufferView;
  76626. }
  76627. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  76628. onLoad();
  76629. }
  76630. }, function () {
  76631. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  76632. });
  76633. };
  76634. for (var buf in gltfRuntime.buffers) {
  76635. hasBuffers = true;
  76636. var buffer = gltfRuntime.buffers[buf];
  76637. if (buffer) {
  76638. processBuffer.bind(this, buf, buffer)();
  76639. }
  76640. else {
  76641. BABYLON.Tools.Error("No buffer named: " + buf);
  76642. }
  76643. }
  76644. if (!hasBuffers) {
  76645. onLoad();
  76646. }
  76647. };
  76648. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  76649. var currentScene = gltfRuntime.currentScene;
  76650. if (currentScene) {
  76651. // Only one scene even if multiple scenes are defined
  76652. for (var i = 0; i < currentScene.nodes.length; i++) {
  76653. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76654. }
  76655. }
  76656. else {
  76657. // Load all scenes
  76658. for (var thing in gltfRuntime.scenes) {
  76659. currentScene = gltfRuntime.scenes[thing];
  76660. for (var i = 0; i < currentScene.nodes.length; i++) {
  76661. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76662. }
  76663. }
  76664. }
  76665. };
  76666. GLTFLoader.Extensions = {};
  76667. return GLTFLoader;
  76668. }());
  76669. GLTF1.GLTFLoader = GLTFLoader;
  76670. ;
  76671. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  76672. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  76673. })(BABYLON || (BABYLON = {}));
  76674. //# sourceMappingURL=babylon.glTFLoader.js.map
  76675. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76676. var BABYLON;
  76677. (function (BABYLON) {
  76678. var GLTF1;
  76679. (function (GLTF1) {
  76680. /**
  76681. * Utils functions for GLTF
  76682. */
  76683. var GLTFUtils = /** @class */ (function () {
  76684. function GLTFUtils() {
  76685. }
  76686. /**
  76687. * Sets the given "parameter" matrix
  76688. * @param scene: the {BABYLON.Scene} object
  76689. * @param source: the source node where to pick the matrix
  76690. * @param parameter: the GLTF technique parameter
  76691. * @param uniformName: the name of the shader's uniform
  76692. * @param shaderMaterial: the shader material
  76693. */
  76694. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  76695. var mat = null;
  76696. if (parameter.semantic === "MODEL") {
  76697. mat = source.getWorldMatrix();
  76698. }
  76699. else if (parameter.semantic === "PROJECTION") {
  76700. mat = scene.getProjectionMatrix();
  76701. }
  76702. else if (parameter.semantic === "VIEW") {
  76703. mat = scene.getViewMatrix();
  76704. }
  76705. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  76706. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  76707. }
  76708. else if (parameter.semantic === "MODELVIEW") {
  76709. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  76710. }
  76711. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  76712. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  76713. }
  76714. else if (parameter.semantic === "MODELINVERSE") {
  76715. mat = source.getWorldMatrix().invert();
  76716. }
  76717. else if (parameter.semantic === "VIEWINVERSE") {
  76718. mat = scene.getViewMatrix().invert();
  76719. }
  76720. else if (parameter.semantic === "PROJECTIONINVERSE") {
  76721. mat = scene.getProjectionMatrix().invert();
  76722. }
  76723. else if (parameter.semantic === "MODELVIEWINVERSE") {
  76724. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  76725. }
  76726. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  76727. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  76728. }
  76729. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  76730. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  76731. }
  76732. else {
  76733. debugger;
  76734. }
  76735. if (mat) {
  76736. switch (parameter.type) {
  76737. case GLTF1.EParameterType.FLOAT_MAT2:
  76738. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  76739. break;
  76740. case GLTF1.EParameterType.FLOAT_MAT3:
  76741. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  76742. break;
  76743. case GLTF1.EParameterType.FLOAT_MAT4:
  76744. shaderMaterial.setMatrix(uniformName, mat);
  76745. break;
  76746. default: break;
  76747. }
  76748. }
  76749. };
  76750. /**
  76751. * Sets the given "parameter" matrix
  76752. * @param shaderMaterial: the shader material
  76753. * @param uniform: the name of the shader's uniform
  76754. * @param value: the value of the uniform
  76755. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  76756. */
  76757. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  76758. switch (type) {
  76759. case GLTF1.EParameterType.FLOAT:
  76760. shaderMaterial.setFloat(uniform, value);
  76761. return true;
  76762. case GLTF1.EParameterType.FLOAT_VEC2:
  76763. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  76764. return true;
  76765. case GLTF1.EParameterType.FLOAT_VEC3:
  76766. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  76767. return true;
  76768. case GLTF1.EParameterType.FLOAT_VEC4:
  76769. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  76770. return true;
  76771. default: return false;
  76772. }
  76773. };
  76774. /**
  76775. * If the uri is a base64 string
  76776. * @param uri: the uri to test
  76777. */
  76778. GLTFUtils.IsBase64 = function (uri) {
  76779. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  76780. };
  76781. /**
  76782. * Decode the base64 uri
  76783. * @param uri: the uri to decode
  76784. */
  76785. GLTFUtils.DecodeBase64 = function (uri) {
  76786. var decodedString = atob(uri.split(",")[1]);
  76787. var bufferLength = decodedString.length;
  76788. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  76789. for (var i = 0; i < bufferLength; i++) {
  76790. bufferView[i] = decodedString.charCodeAt(i);
  76791. }
  76792. return bufferView.buffer;
  76793. };
  76794. /**
  76795. * Returns the wrap mode of the texture
  76796. * @param mode: the mode value
  76797. */
  76798. GLTFUtils.GetWrapMode = function (mode) {
  76799. switch (mode) {
  76800. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  76801. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  76802. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  76803. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  76804. }
  76805. };
  76806. /**
  76807. * Returns the byte stride giving an accessor
  76808. * @param accessor: the GLTF accessor objet
  76809. */
  76810. GLTFUtils.GetByteStrideFromType = function (accessor) {
  76811. // Needs this function since "byteStride" isn't requiered in glTF format
  76812. var type = accessor.type;
  76813. switch (type) {
  76814. case "VEC2": return 2;
  76815. case "VEC3": return 3;
  76816. case "VEC4": return 4;
  76817. case "MAT2": return 4;
  76818. case "MAT3": return 9;
  76819. case "MAT4": return 16;
  76820. default: return 1;
  76821. }
  76822. };
  76823. /**
  76824. * Returns the texture filter mode giving a mode value
  76825. * @param mode: the filter mode value
  76826. */
  76827. GLTFUtils.GetTextureFilterMode = function (mode) {
  76828. switch (mode) {
  76829. case GLTF1.ETextureFilterType.LINEAR:
  76830. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  76831. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  76832. case GLTF1.ETextureFilterType.NEAREST:
  76833. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  76834. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  76835. }
  76836. };
  76837. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  76838. var byteOffset = bufferView.byteOffset + byteOffset;
  76839. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  76840. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  76841. throw new Error("Buffer access is out of range");
  76842. }
  76843. var buffer = loadedBufferView.buffer;
  76844. byteOffset += loadedBufferView.byteOffset;
  76845. switch (componentType) {
  76846. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  76847. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  76848. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  76849. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  76850. default: return new Float32Array(buffer, byteOffset, byteLength);
  76851. }
  76852. };
  76853. /**
  76854. * Returns a buffer from its accessor
  76855. * @param gltfRuntime: the GLTF runtime
  76856. * @param accessor: the GLTF accessor
  76857. */
  76858. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  76859. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  76860. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  76861. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  76862. };
  76863. /**
  76864. * Decodes a buffer view into a string
  76865. * @param view: the buffer view
  76866. */
  76867. GLTFUtils.DecodeBufferToText = function (view) {
  76868. var result = "";
  76869. var length = view.byteLength;
  76870. for (var i = 0; i < length; ++i) {
  76871. result += String.fromCharCode(view[i]);
  76872. }
  76873. return result;
  76874. };
  76875. /**
  76876. * Returns the default material of gltf. Related to
  76877. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  76878. * @param scene: the Babylon.js scene
  76879. */
  76880. GLTFUtils.GetDefaultMaterial = function (scene) {
  76881. if (!GLTFUtils._DefaultMaterial) {
  76882. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  76883. "precision highp float;",
  76884. "",
  76885. "uniform mat4 worldView;",
  76886. "uniform mat4 projection;",
  76887. "",
  76888. "attribute vec3 position;",
  76889. "",
  76890. "void main(void)",
  76891. "{",
  76892. " gl_Position = projection * worldView * vec4(position, 1.0);",
  76893. "}"
  76894. ].join("\n");
  76895. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  76896. "precision highp float;",
  76897. "",
  76898. "uniform vec4 u_emission;",
  76899. "",
  76900. "void main(void)",
  76901. "{",
  76902. " gl_FragColor = u_emission;",
  76903. "}"
  76904. ].join("\n");
  76905. var shaderPath = {
  76906. vertex: "GLTFDefaultMaterial",
  76907. fragment: "GLTFDefaultMaterial"
  76908. };
  76909. var options = {
  76910. attributes: ["position"],
  76911. uniforms: ["worldView", "projection", "u_emission"],
  76912. samplers: new Array(),
  76913. needAlphaBlending: false
  76914. };
  76915. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  76916. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  76917. }
  76918. return GLTFUtils._DefaultMaterial;
  76919. };
  76920. // The GLTF default material
  76921. GLTFUtils._DefaultMaterial = null;
  76922. return GLTFUtils;
  76923. }());
  76924. GLTF1.GLTFUtils = GLTFUtils;
  76925. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  76926. })(BABYLON || (BABYLON = {}));
  76927. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  76928. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76929. var BABYLON;
  76930. (function (BABYLON) {
  76931. var GLTF1;
  76932. (function (GLTF1) {
  76933. var GLTFLoaderExtension = /** @class */ (function () {
  76934. function GLTFLoaderExtension(name) {
  76935. this._name = name;
  76936. }
  76937. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  76938. get: function () {
  76939. return this._name;
  76940. },
  76941. enumerable: true,
  76942. configurable: true
  76943. });
  76944. /**
  76945. * Defines an override for loading the runtime
  76946. * Return true to stop further extensions from loading the runtime
  76947. */
  76948. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  76949. return false;
  76950. };
  76951. /**
  76952. * Defines an onverride for creating gltf runtime
  76953. * Return true to stop further extensions from creating the runtime
  76954. */
  76955. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  76956. return false;
  76957. };
  76958. /**
  76959. * Defines an override for loading buffers
  76960. * Return true to stop further extensions from loading this buffer
  76961. */
  76962. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  76963. return false;
  76964. };
  76965. /**
  76966. * Defines an override for loading texture buffers
  76967. * Return true to stop further extensions from loading this texture data
  76968. */
  76969. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  76970. return false;
  76971. };
  76972. /**
  76973. * Defines an override for creating textures
  76974. * Return true to stop further extensions from loading this texture
  76975. */
  76976. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  76977. return false;
  76978. };
  76979. /**
  76980. * Defines an override for loading shader strings
  76981. * Return true to stop further extensions from loading this shader data
  76982. */
  76983. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  76984. return false;
  76985. };
  76986. /**
  76987. * Defines an override for loading materials
  76988. * Return true to stop further extensions from loading this material
  76989. */
  76990. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  76991. return false;
  76992. };
  76993. // ---------
  76994. // Utilities
  76995. // ---------
  76996. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  76997. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  76998. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  76999. }, function () {
  77000. setTimeout(function () {
  77001. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77002. });
  77003. });
  77004. };
  77005. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77006. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77007. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  77008. }, function () {
  77009. setTimeout(function () {
  77010. onSuccess();
  77011. });
  77012. });
  77013. };
  77014. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77015. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77016. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77017. }, function () {
  77018. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77019. });
  77020. };
  77021. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  77022. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  77023. };
  77024. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77025. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77026. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77027. }, function () {
  77028. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77029. });
  77030. };
  77031. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77032. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77033. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77034. }, function () {
  77035. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77036. });
  77037. };
  77038. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77039. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77040. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77041. }, function () {
  77042. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77043. });
  77044. };
  77045. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77046. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77047. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77048. }, function () {
  77049. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77050. });
  77051. };
  77052. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  77053. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  77054. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  77055. if (func(loaderExtension)) {
  77056. return;
  77057. }
  77058. }
  77059. defaultFunc();
  77060. };
  77061. return GLTFLoaderExtension;
  77062. }());
  77063. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  77064. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77065. })(BABYLON || (BABYLON = {}));
  77066. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  77067. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77068. var BABYLON;
  77069. (function (BABYLON) {
  77070. var GLTF1;
  77071. (function (GLTF1) {
  77072. var BinaryExtensionBufferName = "binary_glTF";
  77073. ;
  77074. ;
  77075. var GLTFBinaryExtension = /** @class */ (function (_super) {
  77076. __extends(GLTFBinaryExtension, _super);
  77077. function GLTFBinaryExtension() {
  77078. return _super.call(this, "KHR_binary_glTF") || this;
  77079. }
  77080. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77081. var extensionsUsed = data.json.extensionsUsed;
  77082. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  77083. return false;
  77084. }
  77085. this._bin = data.bin;
  77086. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77087. return true;
  77088. };
  77089. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77090. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  77091. return false;
  77092. }
  77093. if (id !== BinaryExtensionBufferName) {
  77094. return false;
  77095. }
  77096. onSuccess(this._bin);
  77097. return true;
  77098. };
  77099. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77100. var texture = gltfRuntime.textures[id];
  77101. var source = gltfRuntime.images[texture.source];
  77102. if (!source.extensions || !(this.name in source.extensions)) {
  77103. return false;
  77104. }
  77105. var sourceExt = source.extensions[this.name];
  77106. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  77107. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  77108. onSuccess(buffer);
  77109. return true;
  77110. };
  77111. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77112. var shader = gltfRuntime.shaders[id];
  77113. if (!shader.extensions || !(this.name in shader.extensions)) {
  77114. return false;
  77115. }
  77116. var binaryExtensionShader = shader.extensions[this.name];
  77117. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  77118. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  77119. setTimeout(function () {
  77120. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  77121. onSuccess(shaderString);
  77122. });
  77123. return true;
  77124. };
  77125. return GLTFBinaryExtension;
  77126. }(GLTF1.GLTFLoaderExtension));
  77127. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  77128. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  77129. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77130. })(BABYLON || (BABYLON = {}));
  77131. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  77132. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77133. var BABYLON;
  77134. (function (BABYLON) {
  77135. var GLTF1;
  77136. (function (GLTF1) {
  77137. ;
  77138. ;
  77139. ;
  77140. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  77141. __extends(GLTFMaterialsCommonExtension, _super);
  77142. function GLTFMaterialsCommonExtension() {
  77143. return _super.call(this, "KHR_materials_common") || this;
  77144. }
  77145. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77146. if (!gltfRuntime.extensions)
  77147. return false;
  77148. var extension = gltfRuntime.extensions[this.name];
  77149. if (!extension)
  77150. return false;
  77151. // Create lights
  77152. var lights = extension.lights;
  77153. if (lights) {
  77154. for (var thing in lights) {
  77155. var light = lights[thing];
  77156. switch (light.type) {
  77157. case "ambient":
  77158. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  77159. var ambient = light.ambient;
  77160. if (ambient) {
  77161. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  77162. }
  77163. break;
  77164. case "point":
  77165. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  77166. var point = light.point;
  77167. if (point) {
  77168. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  77169. }
  77170. break;
  77171. case "directional":
  77172. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  77173. var directional = light.directional;
  77174. if (directional) {
  77175. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  77176. }
  77177. break;
  77178. case "spot":
  77179. var spot = light.spot;
  77180. if (spot) {
  77181. 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);
  77182. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  77183. }
  77184. break;
  77185. default:
  77186. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  77187. break;
  77188. }
  77189. }
  77190. }
  77191. return false;
  77192. };
  77193. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77194. var material = gltfRuntime.materials[id];
  77195. if (!material || !material.extensions)
  77196. return false;
  77197. var extension = material.extensions[this.name];
  77198. if (!extension)
  77199. return false;
  77200. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  77201. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77202. if (extension.technique === "CONSTANT") {
  77203. standardMaterial.disableLighting = true;
  77204. }
  77205. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  77206. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  77207. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  77208. // Ambient
  77209. if (typeof extension.values.ambient === "string") {
  77210. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  77211. }
  77212. else {
  77213. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  77214. }
  77215. // Diffuse
  77216. if (typeof extension.values.diffuse === "string") {
  77217. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  77218. }
  77219. else {
  77220. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  77221. }
  77222. // Emission
  77223. if (typeof extension.values.emission === "string") {
  77224. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  77225. }
  77226. else {
  77227. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  77228. }
  77229. // Specular
  77230. if (typeof extension.values.specular === "string") {
  77231. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  77232. }
  77233. else {
  77234. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  77235. }
  77236. return true;
  77237. };
  77238. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  77239. // Create buffer from texture url
  77240. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  77241. // Create texture from buffer
  77242. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  77243. }, onError);
  77244. };
  77245. return GLTFMaterialsCommonExtension;
  77246. }(GLTF1.GLTFLoaderExtension));
  77247. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  77248. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  77249. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77250. })(BABYLON || (BABYLON = {}));
  77251. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  77252. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77253. var BABYLON;
  77254. (function (BABYLON) {
  77255. var GLTF2;
  77256. (function (GLTF2) {
  77257. /**
  77258. * Enums
  77259. */
  77260. var EComponentType;
  77261. (function (EComponentType) {
  77262. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  77263. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  77264. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  77265. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  77266. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  77267. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  77268. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  77269. var EMeshPrimitiveMode;
  77270. (function (EMeshPrimitiveMode) {
  77271. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  77272. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  77273. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  77274. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  77275. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  77276. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  77277. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  77278. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  77279. var ETextureMagFilter;
  77280. (function (ETextureMagFilter) {
  77281. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  77282. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  77283. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  77284. var ETextureMinFilter;
  77285. (function (ETextureMinFilter) {
  77286. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  77287. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  77288. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  77289. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  77290. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  77291. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  77292. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  77293. var ETextureWrapMode;
  77294. (function (ETextureWrapMode) {
  77295. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  77296. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  77297. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  77298. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  77299. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  77300. })(BABYLON || (BABYLON = {}));
  77301. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  77302. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77303. var BABYLON;
  77304. (function (BABYLON) {
  77305. var GLTF2;
  77306. (function (GLTF2) {
  77307. var GLTFLoaderTracker = /** @class */ (function () {
  77308. function GLTFLoaderTracker(onComplete) {
  77309. this._pendingCount = 0;
  77310. this._callback = onComplete;
  77311. }
  77312. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  77313. this._pendingCount++;
  77314. };
  77315. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  77316. if (--this._pendingCount === 0) {
  77317. this._callback();
  77318. }
  77319. };
  77320. return GLTFLoaderTracker;
  77321. }());
  77322. var GLTFLoader = /** @class */ (function () {
  77323. function GLTFLoader(parent) {
  77324. this._disposed = false;
  77325. this._renderReady = false;
  77326. this._requests = new Array();
  77327. this._renderReadyObservable = new BABYLON.Observable();
  77328. // Count of pending work that needs to complete before the asset is rendered.
  77329. this._renderPendingCount = 0;
  77330. // Count of pending work that needs to complete before the loader is disposed.
  77331. this._loaderPendingCount = 0;
  77332. this._loaderTrackers = new Array();
  77333. this._parent = parent;
  77334. }
  77335. GLTFLoader.RegisterExtension = function (extension) {
  77336. if (GLTFLoader.Extensions[extension.name]) {
  77337. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  77338. return;
  77339. }
  77340. GLTFLoader.Extensions[extension.name] = extension;
  77341. // Keep the order of registration so that extensions registered first are called first.
  77342. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  77343. };
  77344. GLTFLoader.prototype.dispose = function () {
  77345. if (this._disposed) {
  77346. return;
  77347. }
  77348. this._disposed = true;
  77349. // Abort requests that are not complete
  77350. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  77351. var request = _a[_i];
  77352. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  77353. request.abort();
  77354. }
  77355. }
  77356. // Revoke object urls created during load
  77357. if (this._gltf.textures) {
  77358. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  77359. var texture = _c[_b];
  77360. if (texture.url) {
  77361. URL.revokeObjectURL(texture.url);
  77362. }
  77363. }
  77364. }
  77365. this._gltf = undefined;
  77366. this._babylonScene = undefined;
  77367. this._parent = undefined;
  77368. this._rootUrl = undefined;
  77369. this._defaultMaterial = undefined;
  77370. this._rootNode = undefined;
  77371. this._successCallback = undefined;
  77372. this._progressCallback = undefined;
  77373. this._errorCallback = undefined;
  77374. this._renderReady = false;
  77375. this._requests = undefined;
  77376. this._renderReadyObservable = undefined;
  77377. this._renderPendingCount = 0;
  77378. this._loaderPendingCount = 0;
  77379. this._loaderTrackers = undefined;
  77380. };
  77381. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77382. var _this = this;
  77383. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  77384. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  77385. }, onProgress, onError);
  77386. };
  77387. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77388. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  77389. };
  77390. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77391. var _this = this;
  77392. this._tryCatchOnError(function () {
  77393. _this._loadData(data);
  77394. _this._babylonScene = scene;
  77395. _this._rootUrl = rootUrl;
  77396. _this._successCallback = onSuccess;
  77397. _this._progressCallback = onProgress;
  77398. _this._errorCallback = onError;
  77399. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  77400. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  77401. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  77402. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  77403. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  77404. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  77405. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  77406. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  77407. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  77408. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  77409. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  77410. _this._addPendingData(_this);
  77411. _this._loadDefaultScene(nodeNames);
  77412. _this._loadAnimations();
  77413. _this._removePendingData(_this);
  77414. });
  77415. };
  77416. GLTFLoader.prototype._onError = function (message) {
  77417. if (this._disposed) {
  77418. return;
  77419. }
  77420. BABYLON.Tools.Error("glTF Loader: " + message);
  77421. if (this._errorCallback) {
  77422. this._errorCallback(message);
  77423. }
  77424. this.dispose();
  77425. };
  77426. GLTFLoader.prototype._onProgress = function (event) {
  77427. if (this._disposed) {
  77428. return;
  77429. }
  77430. if (this._progressCallback) {
  77431. this._progressCallback(event);
  77432. }
  77433. };
  77434. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  77435. if (this._renderReady) {
  77436. func();
  77437. }
  77438. else {
  77439. this._renderReadyObservable.add(func);
  77440. }
  77441. };
  77442. GLTFLoader.prototype._onRenderReady = function () {
  77443. if (this._rootNode.babylonMesh) {
  77444. this._rootNode.babylonMesh.setEnabled(true);
  77445. }
  77446. this._startAnimations();
  77447. this._successCallback();
  77448. this._renderReadyObservable.notifyObservers(this);
  77449. };
  77450. GLTFLoader.prototype._onComplete = function () {
  77451. if (this._parent.onComplete) {
  77452. this._parent.onComplete();
  77453. }
  77454. this.dispose();
  77455. };
  77456. GLTFLoader.prototype._loadData = function (data) {
  77457. this._gltf = data.json;
  77458. if (data.bin) {
  77459. var buffers = this._gltf.buffers;
  77460. if (buffers && buffers[0] && !buffers[0].uri) {
  77461. var binaryBuffer = buffers[0];
  77462. if (binaryBuffer.byteLength != data.bin.byteLength) {
  77463. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  77464. }
  77465. binaryBuffer.loadedData = data.bin;
  77466. }
  77467. else {
  77468. BABYLON.Tools.Warn("Unexpected BIN chunk");
  77469. }
  77470. }
  77471. };
  77472. GLTFLoader.prototype._getMeshes = function () {
  77473. var meshes = [this._rootNode.babylonMesh || null];
  77474. var nodes = this._gltf.nodes;
  77475. if (nodes) {
  77476. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  77477. var node = nodes_1[_i];
  77478. if (node.babylonMesh) {
  77479. meshes.push(node.babylonMesh);
  77480. }
  77481. }
  77482. }
  77483. return meshes;
  77484. };
  77485. GLTFLoader.prototype._getSkeletons = function () {
  77486. var skeletons = new Array();
  77487. var skins = this._gltf.skins;
  77488. if (skins) {
  77489. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  77490. var skin = skins_1[_i];
  77491. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77492. skeletons.push(skin.babylonSkeleton);
  77493. }
  77494. }
  77495. }
  77496. return skeletons;
  77497. };
  77498. GLTFLoader.prototype._getAnimationTargets = function () {
  77499. var targets = new Array();
  77500. var animations = this._gltf.animations;
  77501. if (animations) {
  77502. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  77503. var animation = animations_1[_i];
  77504. targets.push.apply(targets, animation.targets);
  77505. }
  77506. }
  77507. return targets;
  77508. };
  77509. GLTFLoader.prototype._startAnimations = function () {
  77510. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  77511. var target = _a[_i];
  77512. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  77513. }
  77514. };
  77515. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  77516. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  77517. if (!scene) {
  77518. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  77519. }
  77520. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  77521. };
  77522. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  77523. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  77524. switch (this._parent.coordinateSystemMode) {
  77525. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  77526. if (!this._babylonScene.useRightHandedSystem && this._rootNode.babylonMesh) {
  77527. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  77528. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  77529. }
  77530. break;
  77531. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  77532. // do nothing
  77533. break;
  77534. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  77535. this._babylonScene.useRightHandedSystem = true;
  77536. break;
  77537. default:
  77538. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  77539. return;
  77540. }
  77541. var nodeIndices = scene.nodes;
  77542. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  77543. node.parent = parentNode;
  77544. return true;
  77545. }, this._rootNode);
  77546. if (nodeNames) {
  77547. if (!(nodeNames instanceof Array)) {
  77548. nodeNames = [nodeNames];
  77549. }
  77550. var filteredNodeIndices_1 = new Array();
  77551. this._traverseNodes(context, nodeIndices, function (node) {
  77552. if (nodeNames.indexOf(node.name) !== -1) {
  77553. filteredNodeIndices_1.push(node.index);
  77554. return false;
  77555. }
  77556. return true;
  77557. }, this._rootNode);
  77558. nodeIndices = filteredNodeIndices_1;
  77559. }
  77560. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  77561. var index = nodeIndices_1[_i];
  77562. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  77563. if (!node) {
  77564. throw new Error(context + ": Failed to find node " + index);
  77565. }
  77566. this._loadNode("#/nodes/" + index, node);
  77567. }
  77568. // Disable the root mesh until the asset is ready to render.
  77569. if (this._rootNode.babylonMesh) {
  77570. this._rootNode.babylonMesh.setEnabled(false);
  77571. }
  77572. };
  77573. GLTFLoader.prototype._loadNode = function (context, node) {
  77574. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  77575. return;
  77576. }
  77577. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  77578. this._loadTransform(node);
  77579. if (node.mesh != null) {
  77580. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  77581. if (!mesh) {
  77582. throw new Error(context + ": Failed to find mesh " + node.mesh);
  77583. }
  77584. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  77585. }
  77586. node.babylonMesh.parent = (node.parent ? node.parent.babylonMesh : null);
  77587. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  77588. node.babylonAnimationTargets.push(node.babylonMesh);
  77589. if (node.skin != null) {
  77590. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  77591. if (!skin) {
  77592. throw new Error(context + ": Failed to find skin " + node.skin);
  77593. }
  77594. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  77595. }
  77596. if (node.camera != null) {
  77597. // TODO: handle cameras
  77598. }
  77599. if (node.children) {
  77600. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  77601. var index = _a[_i];
  77602. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  77603. if (!childNode) {
  77604. throw new Error(context + ": Failed to find child node " + index);
  77605. }
  77606. this._loadNode("#/nodes/" + index, childNode);
  77607. }
  77608. }
  77609. };
  77610. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  77611. var _this = this;
  77612. if (!node.babylonMesh) {
  77613. return;
  77614. }
  77615. node.babylonMesh.name = node.babylonMesh.name || mesh.name || "";
  77616. var primitives = mesh.primitives;
  77617. if (!primitives || primitives.length === 0) {
  77618. throw new Error(context + ": Primitives are missing");
  77619. }
  77620. this._createMorphTargets(context, node, mesh);
  77621. this._loadAllVertexDataAsync(context, mesh, function () {
  77622. if (!node.babylonMesh) {
  77623. return;
  77624. }
  77625. _this._loadMorphTargets(context, node, mesh);
  77626. var vertexData = new BABYLON.VertexData();
  77627. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  77628. var primitive = primitives_1[_i];
  77629. vertexData.merge(primitive.vertexData);
  77630. }
  77631. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  77632. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  77633. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  77634. node.babylonMesh.subMeshes = [];
  77635. var verticesStart = 0;
  77636. var indicesStart = 0;
  77637. for (var index = 0; index < primitives.length; index++) {
  77638. var vertexData_1 = primitives[index].vertexData;
  77639. var verticesCount = vertexData_1.positions.length;
  77640. var indicesCount = vertexData_1.indices.length;
  77641. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  77642. verticesStart += verticesCount;
  77643. indicesStart += indicesCount;
  77644. }
  77645. ;
  77646. });
  77647. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  77648. node.babylonMesh.material = multiMaterial;
  77649. var subMaterials = multiMaterial.subMaterials;
  77650. var _loop_1 = function (index) {
  77651. var primitive = primitives[index];
  77652. if (primitive.material == null) {
  77653. subMaterials[index] = this_1._getDefaultMaterial();
  77654. }
  77655. else {
  77656. var material_1 = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.materials, primitive.material);
  77657. if (!material_1) {
  77658. throw new Error(context + ": Failed to find material " + primitive.material);
  77659. }
  77660. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  77661. if (isNew && _this._parent.onMaterialLoaded) {
  77662. _this._parent.onMaterialLoaded(babylonMaterial);
  77663. }
  77664. if (_this._parent.onBeforeMaterialReadyAsync) {
  77665. _this._addLoaderPendingData(material_1);
  77666. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  77667. _this._tryCatchOnError(function () {
  77668. subMaterials[index] = babylonMaterial;
  77669. _this._removeLoaderPendingData(material_1);
  77670. });
  77671. });
  77672. }
  77673. else {
  77674. subMaterials[index] = babylonMaterial;
  77675. }
  77676. });
  77677. }
  77678. };
  77679. var this_1 = this;
  77680. for (var index = 0; index < primitives.length; index++) {
  77681. _loop_1(index);
  77682. }
  77683. ;
  77684. };
  77685. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  77686. var primitives = mesh.primitives;
  77687. var numRemainingPrimitives = primitives.length;
  77688. var _loop_2 = function (index) {
  77689. var primitive = primitives[index];
  77690. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  77691. primitive.vertexData = vertexData;
  77692. if (--numRemainingPrimitives === 0) {
  77693. onSuccess();
  77694. }
  77695. });
  77696. };
  77697. var this_2 = this;
  77698. for (var index = 0; index < primitives.length; index++) {
  77699. _loop_2(index);
  77700. }
  77701. };
  77702. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  77703. var _this = this;
  77704. var attributes = primitive.attributes;
  77705. if (!attributes) {
  77706. throw new Error(context + ": Attributes are missing");
  77707. }
  77708. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  77709. // TODO: handle other primitive modes
  77710. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  77711. }
  77712. var vertexData = new BABYLON.VertexData();
  77713. var numRemainingAttributes = Object.keys(attributes).length;
  77714. var _loop_3 = function (attribute) {
  77715. var accessor = GLTF2.GLTFUtils.GetArrayItem(this_3._gltf.accessors, attributes[attribute]);
  77716. if (!accessor) {
  77717. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  77718. }
  77719. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  77720. switch (attribute) {
  77721. case "NORMAL":
  77722. vertexData.normals = data;
  77723. break;
  77724. case "POSITION":
  77725. vertexData.positions = data;
  77726. break;
  77727. case "TANGENT":
  77728. vertexData.tangents = data;
  77729. break;
  77730. case "TEXCOORD_0":
  77731. vertexData.uvs = data;
  77732. break;
  77733. case "TEXCOORD_1":
  77734. vertexData.uvs2 = data;
  77735. break;
  77736. case "JOINTS_0":
  77737. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  77738. break;
  77739. case "WEIGHTS_0":
  77740. vertexData.matricesWeights = data;
  77741. break;
  77742. case "COLOR_0":
  77743. vertexData.colors = data;
  77744. break;
  77745. default:
  77746. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  77747. break;
  77748. }
  77749. if (--numRemainingAttributes === 0) {
  77750. if (primitive.indices == null) {
  77751. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  77752. for (var i = 0; i < vertexData.indices.length; i++) {
  77753. vertexData.indices[i] = i;
  77754. }
  77755. onSuccess(vertexData);
  77756. }
  77757. else {
  77758. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  77759. if (!indicesAccessor) {
  77760. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  77761. }
  77762. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  77763. vertexData.indices = data;
  77764. onSuccess(vertexData);
  77765. });
  77766. }
  77767. }
  77768. });
  77769. };
  77770. var this_3 = this;
  77771. for (var attribute in attributes) {
  77772. _loop_3(attribute);
  77773. }
  77774. };
  77775. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  77776. var primitives = mesh.primitives;
  77777. var targets = primitives[0].targets;
  77778. if (!targets || !node.babylonMesh) {
  77779. return;
  77780. }
  77781. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  77782. var primitive = primitives_2[_i];
  77783. if (!primitive.targets || primitive.targets.length != targets.length) {
  77784. throw new Error(context + ": All primitives are required to list the same number of targets");
  77785. }
  77786. }
  77787. var morphTargetManager = new BABYLON.MorphTargetManager();
  77788. node.babylonMesh.morphTargetManager = morphTargetManager;
  77789. for (var index = 0; index < targets.length; index++) {
  77790. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  77791. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  77792. }
  77793. };
  77794. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  77795. if (!node.babylonMesh) {
  77796. return;
  77797. }
  77798. var morphTargetManager = node.babylonMesh.morphTargetManager;
  77799. if (!morphTargetManager) {
  77800. return;
  77801. }
  77802. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  77803. var numTargets = morphTargetManager.numTargets;
  77804. for (var index = 0; index < numTargets; index++) {
  77805. var vertexData = new BABYLON.VertexData();
  77806. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  77807. var primitive = _a[_i];
  77808. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  77809. }
  77810. var target = morphTargetManager.getTarget(index);
  77811. target.setNormals(vertexData.normals);
  77812. target.setPositions(vertexData.positions);
  77813. target.setTangents(vertexData.tangents);
  77814. }
  77815. });
  77816. };
  77817. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  77818. if (!node.babylonMesh || !node.babylonMesh.morphTargetManager) {
  77819. return;
  77820. }
  77821. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  77822. var _loop_4 = function (primitive) {
  77823. var targets = primitive.targets;
  77824. if (!targets) {
  77825. return "continue";
  77826. }
  77827. primitive.targetsVertexData = new Array(targets.length);
  77828. var _loop_5 = function (index) {
  77829. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  77830. primitive.targetsVertexData[index] = vertexData;
  77831. if (--numRemainingTargets === 0) {
  77832. onSuccess();
  77833. }
  77834. });
  77835. };
  77836. for (var index = 0; index < targets.length; index++) {
  77837. _loop_5(index);
  77838. }
  77839. };
  77840. var this_4 = this;
  77841. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  77842. var primitive = _a[_i];
  77843. _loop_4(primitive);
  77844. }
  77845. };
  77846. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  77847. var targetVertexData = new BABYLON.VertexData();
  77848. var numRemainingAttributes = Object.keys(attributes).length;
  77849. var _loop_6 = function (attribute) {
  77850. var accessor = GLTF2.GLTFUtils.GetArrayItem(this_5._gltf.accessors, attributes[attribute]);
  77851. if (!accessor) {
  77852. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  77853. }
  77854. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  77855. // glTF stores morph target information as deltas while babylon.js expects the final data.
  77856. // As a result we have to add the original data to the delta to calculate the final data.
  77857. var values = data;
  77858. switch (attribute) {
  77859. case "NORMAL":
  77860. for (var i = 0; i < values.length; i++) {
  77861. values[i] += vertexData.normals[i];
  77862. }
  77863. targetVertexData.normals = values;
  77864. break;
  77865. case "POSITION":
  77866. for (var i = 0; i < values.length; i++) {
  77867. values[i] += vertexData.positions[i];
  77868. }
  77869. targetVertexData.positions = values;
  77870. break;
  77871. case "TANGENT":
  77872. // Tangent data for morph targets is stored as xyz delta.
  77873. // The vertexData.tangent is stored as xyzw.
  77874. // So we need to skip every fourth vertexData.tangent.
  77875. for (var i = 0, j = 0; i < values.length; i++, j++) {
  77876. values[i] += vertexData.tangents[j];
  77877. if ((i + 1) % 3 == 0) {
  77878. j++;
  77879. }
  77880. }
  77881. targetVertexData.tangents = values;
  77882. break;
  77883. default:
  77884. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  77885. break;
  77886. }
  77887. if (--numRemainingAttributes === 0) {
  77888. onSuccess(targetVertexData);
  77889. }
  77890. });
  77891. };
  77892. var this_5 = this;
  77893. for (var attribute in attributes) {
  77894. _loop_6(attribute);
  77895. }
  77896. };
  77897. GLTFLoader.prototype._loadTransform = function (node) {
  77898. if (!node.babylonMesh) {
  77899. return;
  77900. }
  77901. var position = BABYLON.Vector3.Zero();
  77902. var rotation = BABYLON.Quaternion.Identity();
  77903. var scaling = BABYLON.Vector3.One();
  77904. if (node.matrix) {
  77905. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  77906. matrix.decompose(scaling, rotation, position);
  77907. }
  77908. else {
  77909. if (node.translation)
  77910. position = BABYLON.Vector3.FromArray(node.translation);
  77911. if (node.rotation)
  77912. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  77913. if (node.scale)
  77914. scaling = BABYLON.Vector3.FromArray(node.scale);
  77915. }
  77916. node.babylonMesh.position = position;
  77917. node.babylonMesh.rotationQuaternion = rotation;
  77918. node.babylonMesh.scaling = scaling;
  77919. };
  77920. GLTFLoader.prototype._loadSkin = function (context, skin) {
  77921. var _this = this;
  77922. var skeletonId = "skeleton" + skin.index;
  77923. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  77924. if (skin.inverseBindMatrices == null) {
  77925. this._loadBones(context, skin, null);
  77926. }
  77927. else {
  77928. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  77929. if (!accessor) {
  77930. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  77931. }
  77932. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  77933. _this._loadBones(context, skin, data);
  77934. });
  77935. }
  77936. return skin.babylonSkeleton;
  77937. };
  77938. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  77939. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  77940. node.babylonBones = node.babylonBones || {};
  77941. node.babylonBones[skin.index] = babylonBone;
  77942. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  77943. node.babylonAnimationTargets.push(babylonBone);
  77944. return babylonBone;
  77945. };
  77946. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  77947. var babylonBones = {};
  77948. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  77949. var index = _a[_i];
  77950. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  77951. if (!node) {
  77952. throw new Error(context + ": Failed to find joint " + index);
  77953. }
  77954. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  77955. }
  77956. };
  77957. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  77958. var babylonBone = babylonBones[node.index];
  77959. if (babylonBone) {
  77960. return babylonBone;
  77961. }
  77962. var boneIndex = skin.joints.indexOf(node.index);
  77963. var baseMatrix = BABYLON.Matrix.Identity();
  77964. if (inverseBindMatrixData && boneIndex !== -1) {
  77965. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  77966. baseMatrix.invertToRef(baseMatrix);
  77967. }
  77968. var babylonParentBone = null;
  77969. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  77970. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  77971. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  77972. }
  77973. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  77974. babylonBones[node.index] = babylonBone;
  77975. return babylonBone;
  77976. };
  77977. GLTFLoader.prototype._getNodeMatrix = function (node) {
  77978. return node.matrix ?
  77979. BABYLON.Matrix.FromArray(node.matrix) :
  77980. 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());
  77981. };
  77982. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  77983. if (parentNode === void 0) { parentNode = null; }
  77984. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  77985. var index = indices_1[_i];
  77986. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  77987. if (!node) {
  77988. throw new Error(context + ": Failed to find node " + index);
  77989. }
  77990. this._traverseNode(context, node, action, parentNode);
  77991. }
  77992. };
  77993. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  77994. if (parentNode === void 0) { parentNode = null; }
  77995. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  77996. return;
  77997. }
  77998. if (!action(node, parentNode)) {
  77999. return;
  78000. }
  78001. if (node.children) {
  78002. this._traverseNodes(context, node.children, action, node);
  78003. }
  78004. };
  78005. GLTFLoader.prototype._loadAnimations = function () {
  78006. var animations = this._gltf.animations;
  78007. if (!animations) {
  78008. return;
  78009. }
  78010. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  78011. var animation = animations[animationIndex];
  78012. var context = "#/animations/" + animationIndex;
  78013. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  78014. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  78015. if (!channel) {
  78016. throw new Error(context + ": Failed to find channel " + channelIndex);
  78017. }
  78018. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  78019. if (!sampler) {
  78020. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  78021. }
  78022. this._loadAnimationChannel(animation, context + "/channels/" + channelIndex, channel, context + "/samplers/" + channel.sampler, sampler);
  78023. }
  78024. }
  78025. };
  78026. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  78027. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  78028. if (!targetNode) {
  78029. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  78030. }
  78031. var targetPath;
  78032. var animationType;
  78033. switch (channel.target.path) {
  78034. case "translation":
  78035. targetPath = "position";
  78036. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78037. break;
  78038. case "rotation":
  78039. targetPath = "rotationQuaternion";
  78040. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  78041. break;
  78042. case "scale":
  78043. targetPath = "scaling";
  78044. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78045. break;
  78046. case "weights":
  78047. targetPath = "influence";
  78048. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  78049. break;
  78050. default:
  78051. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  78052. }
  78053. var inputData;
  78054. var outputData;
  78055. var checkSuccess = function () {
  78056. if (!inputData || !outputData) {
  78057. return;
  78058. }
  78059. var outputBufferOffset = 0;
  78060. var getNextOutputValue;
  78061. switch (targetPath) {
  78062. case "position":
  78063. getNextOutputValue = function () {
  78064. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  78065. outputBufferOffset += 3;
  78066. return value;
  78067. };
  78068. break;
  78069. case "rotationQuaternion":
  78070. getNextOutputValue = function () {
  78071. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  78072. outputBufferOffset += 4;
  78073. return value;
  78074. };
  78075. break;
  78076. case "scaling":
  78077. getNextOutputValue = function () {
  78078. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  78079. outputBufferOffset += 3;
  78080. return value;
  78081. };
  78082. break;
  78083. case "influence":
  78084. getNextOutputValue = function () {
  78085. if (!targetNode.babylonMesh || !targetNode.babylonMesh.morphTargetManager) {
  78086. return;
  78087. }
  78088. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  78089. var value = new Array(numTargets);
  78090. for (var i = 0; i < numTargets; i++) {
  78091. value[i] = outputData[outputBufferOffset++];
  78092. }
  78093. return value;
  78094. };
  78095. break;
  78096. }
  78097. var getNextKey;
  78098. switch (sampler.interpolation) {
  78099. case "LINEAR":
  78100. getNextKey = function (frameIndex) { return ({
  78101. frame: inputData[frameIndex],
  78102. value: getNextOutputValue()
  78103. }); };
  78104. break;
  78105. case "CUBICSPLINE":
  78106. getNextKey = function (frameIndex) { return ({
  78107. frame: inputData[frameIndex],
  78108. inTangent: getNextOutputValue(),
  78109. value: getNextOutputValue(),
  78110. outTangent: getNextOutputValue()
  78111. }); };
  78112. break;
  78113. default:
  78114. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  78115. }
  78116. ;
  78117. var keys = new Array(inputData.length);
  78118. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  78119. keys[frameIndex] = getNextKey(frameIndex);
  78120. }
  78121. animation.targets = animation.targets || [];
  78122. if (targetPath === "influence" && targetNode.babylonMesh && targetNode.babylonMesh.morphTargetManager) {
  78123. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  78124. var _loop_7 = function (targetIndex) {
  78125. var morphTarget = morphTargetManager.getTarget(targetIndex);
  78126. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  78127. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  78128. babylonAnimation.setKeys(keys.map(function (key) { return ({
  78129. frame: key.frame,
  78130. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  78131. value: key.value[targetIndex],
  78132. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  78133. }); }));
  78134. morphTarget.animations.push(babylonAnimation);
  78135. animation.targets.push(morphTarget);
  78136. };
  78137. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  78138. _loop_7(targetIndex);
  78139. }
  78140. }
  78141. else if (targetNode.babylonAnimationTargets) {
  78142. var animationName = animation.name || "anim" + animation.index;
  78143. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  78144. babylonAnimation.setKeys(keys);
  78145. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  78146. var target = _a[_i];
  78147. target.animations.push(babylonAnimation.clone());
  78148. animation.targets.push(target);
  78149. }
  78150. }
  78151. };
  78152. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  78153. if (!inputAccessor) {
  78154. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  78155. }
  78156. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  78157. inputData = data;
  78158. checkSuccess();
  78159. });
  78160. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  78161. if (!outputAccessor) {
  78162. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  78163. }
  78164. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  78165. outputData = data;
  78166. checkSuccess();
  78167. });
  78168. };
  78169. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  78170. var _this = this;
  78171. this._addPendingData(buffer);
  78172. if (buffer.loadedData) {
  78173. onSuccess(buffer.loadedData);
  78174. this._removePendingData(buffer);
  78175. }
  78176. else if (buffer.loadedObservable) {
  78177. buffer.loadedObservable.add(function (buffer) {
  78178. onSuccess(buffer.loadedData);
  78179. _this._removePendingData(buffer);
  78180. });
  78181. }
  78182. else {
  78183. if (!buffer.uri) {
  78184. throw new Error(context + ": Uri is missing");
  78185. }
  78186. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  78187. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  78188. buffer.loadedData = new Uint8Array(data);
  78189. onSuccess(buffer.loadedData);
  78190. this._removePendingData(buffer);
  78191. }
  78192. else {
  78193. buffer.loadedObservable = new BABYLON.Observable();
  78194. buffer.loadedObservable.add(function (buffer) {
  78195. onSuccess(buffer.loadedData);
  78196. _this._removePendingData(buffer);
  78197. });
  78198. this._loadUri(context, buffer.uri, function (data) {
  78199. buffer.loadedData = data;
  78200. if (buffer.loadedObservable) {
  78201. buffer.loadedObservable.notifyObservers(buffer);
  78202. buffer.loadedObservable = undefined;
  78203. }
  78204. });
  78205. }
  78206. }
  78207. };
  78208. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  78209. var _this = this;
  78210. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  78211. if (!buffer) {
  78212. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  78213. }
  78214. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  78215. if (_this._disposed || !bufferData) {
  78216. return;
  78217. }
  78218. var data;
  78219. try {
  78220. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  78221. }
  78222. catch (e) {
  78223. throw new Error(context + ": " + e.message);
  78224. }
  78225. onSuccess(data);
  78226. });
  78227. };
  78228. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  78229. var _this = this;
  78230. if (accessor.sparse) {
  78231. throw new Error(context + ": Sparse accessors are not currently supported");
  78232. }
  78233. if (accessor.normalized) {
  78234. throw new Error(context + ": Normalized accessors are not currently supported");
  78235. }
  78236. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  78237. if (!bufferView) {
  78238. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  78239. }
  78240. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  78241. var numComponents = _this._getNumComponentsOfType(accessor.type);
  78242. if (numComponents === 0) {
  78243. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  78244. }
  78245. var data;
  78246. var byteOffset = accessor.byteOffset;
  78247. var byteStride = bufferView.byteStride;
  78248. try {
  78249. switch (accessor.componentType) {
  78250. case GLTF2.EComponentType.BYTE:
  78251. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78252. break;
  78253. case GLTF2.EComponentType.UNSIGNED_BYTE:
  78254. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78255. break;
  78256. case GLTF2.EComponentType.SHORT:
  78257. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78258. break;
  78259. case GLTF2.EComponentType.UNSIGNED_SHORT:
  78260. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78261. break;
  78262. case GLTF2.EComponentType.UNSIGNED_INT:
  78263. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78264. break;
  78265. case GLTF2.EComponentType.FLOAT:
  78266. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78267. break;
  78268. default:
  78269. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78270. }
  78271. }
  78272. catch (e) {
  78273. throw new Error(context + ": " + e);
  78274. }
  78275. onSuccess(data);
  78276. });
  78277. };
  78278. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  78279. switch (type) {
  78280. case "SCALAR": return 1;
  78281. case "VEC2": return 2;
  78282. case "VEC3": return 3;
  78283. case "VEC4": return 4;
  78284. case "MAT2": return 4;
  78285. case "MAT3": return 9;
  78286. case "MAT4": return 16;
  78287. }
  78288. return 0;
  78289. };
  78290. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  78291. byteOffset = data.byteOffset + (byteOffset || 0);
  78292. var targetLength = count * numComponents;
  78293. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  78294. return new typedArray(data.buffer, byteOffset, targetLength);
  78295. }
  78296. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  78297. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  78298. var targetBuffer = new typedArray(targetLength);
  78299. var sourceIndex = 0;
  78300. var targetIndex = 0;
  78301. while (targetIndex < targetLength) {
  78302. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  78303. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  78304. targetIndex++;
  78305. }
  78306. sourceIndex += elementStride;
  78307. }
  78308. return targetBuffer;
  78309. };
  78310. GLTFLoader.prototype._addPendingData = function (data) {
  78311. if (!this._renderReady) {
  78312. this._renderPendingCount++;
  78313. }
  78314. this._addLoaderPendingData(data);
  78315. };
  78316. GLTFLoader.prototype._removePendingData = function (data) {
  78317. if (!this._renderReady) {
  78318. if (--this._renderPendingCount === 0) {
  78319. this._renderReady = true;
  78320. this._onRenderReady();
  78321. }
  78322. }
  78323. this._removeLoaderPendingData(data);
  78324. };
  78325. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  78326. this._loaderPendingCount++;
  78327. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  78328. var tracker = _a[_i];
  78329. tracker._addPendingData(data);
  78330. }
  78331. };
  78332. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  78333. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  78334. var tracker = _a[_i];
  78335. tracker._removePendingData(data);
  78336. }
  78337. if (--this._loaderPendingCount === 0) {
  78338. this._onComplete();
  78339. }
  78340. };
  78341. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  78342. var _this = this;
  78343. var tracker = new GLTFLoaderTracker(function () {
  78344. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  78345. onComplete();
  78346. });
  78347. this._loaderTrackers.push(tracker);
  78348. this._addLoaderPendingData(tracker);
  78349. action();
  78350. this._removeLoaderPendingData(tracker);
  78351. };
  78352. GLTFLoader.prototype._getDefaultMaterial = function () {
  78353. if (!this._defaultMaterial) {
  78354. var id = "__gltf_default";
  78355. var material = this._babylonScene.getMaterialByName(id);
  78356. if (!material) {
  78357. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  78358. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78359. material.metallic = 1;
  78360. material.roughness = 1;
  78361. }
  78362. this._defaultMaterial = material;
  78363. }
  78364. return this._defaultMaterial;
  78365. };
  78366. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  78367. var babylonMaterial = material.babylonMaterial;
  78368. // Ensure metallic workflow
  78369. babylonMaterial.metallic = 1;
  78370. babylonMaterial.roughness = 1;
  78371. var properties = material.pbrMetallicRoughness;
  78372. if (!properties) {
  78373. return;
  78374. }
  78375. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  78376. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  78377. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  78378. if (properties.baseColorTexture && properties.baseColorTexture.texCoord) {
  78379. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  78380. if (!texture) {
  78381. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  78382. }
  78383. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  78384. }
  78385. if (properties.metallicRoughnessTexture && properties.metallicRoughnessTexture.texCoord) {
  78386. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  78387. if (!texture) {
  78388. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  78389. }
  78390. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  78391. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  78392. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  78393. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  78394. }
  78395. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  78396. };
  78397. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  78398. if (material.babylonMaterial) {
  78399. assign(material.babylonMaterial, false);
  78400. return;
  78401. }
  78402. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  78403. return;
  78404. }
  78405. this._createPbrMaterial(material);
  78406. this._loadMaterialBaseProperties(context, material);
  78407. this._loadMaterialMetallicRoughnessProperties(context, material);
  78408. if (material.babylonMaterial) {
  78409. assign(material.babylonMaterial, true);
  78410. }
  78411. };
  78412. GLTFLoader.prototype._createPbrMaterial = function (material) {
  78413. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  78414. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78415. material.babylonMaterial = babylonMaterial;
  78416. };
  78417. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  78418. var babylonMaterial = material.babylonMaterial;
  78419. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  78420. if (material.doubleSided) {
  78421. babylonMaterial.backFaceCulling = false;
  78422. babylonMaterial.twoSidedLighting = true;
  78423. }
  78424. if (material.normalTexture && material.normalTexture.texCoord) {
  78425. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  78426. if (!texture) {
  78427. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  78428. }
  78429. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  78430. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  78431. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  78432. if (material.normalTexture.scale != null) {
  78433. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  78434. }
  78435. }
  78436. if (material.occlusionTexture && material.occlusionTexture.texCoord) {
  78437. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  78438. if (!texture) {
  78439. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  78440. }
  78441. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  78442. babylonMaterial.useAmbientInGrayScale = true;
  78443. if (material.occlusionTexture.strength != null) {
  78444. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  78445. }
  78446. }
  78447. if (material.emissiveTexture && material.emissiveTexture.texCoord) {
  78448. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  78449. if (!texture) {
  78450. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  78451. }
  78452. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  78453. }
  78454. };
  78455. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  78456. var babylonMaterial = material.babylonMaterial;
  78457. var alphaMode = material.alphaMode || "OPAQUE";
  78458. switch (alphaMode) {
  78459. case "OPAQUE":
  78460. // default is opaque
  78461. break;
  78462. case "MASK":
  78463. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  78464. if (colorFactor) {
  78465. if (colorFactor[3] == 0) {
  78466. babylonMaterial.alphaCutOff = 1;
  78467. }
  78468. else {
  78469. babylonMaterial.alphaCutOff /= colorFactor[3];
  78470. }
  78471. }
  78472. if (babylonMaterial.albedoTexture) {
  78473. babylonMaterial.albedoTexture.hasAlpha = true;
  78474. }
  78475. break;
  78476. case "BLEND":
  78477. if (colorFactor) {
  78478. babylonMaterial.alpha = colorFactor[3];
  78479. }
  78480. if (babylonMaterial.albedoTexture) {
  78481. babylonMaterial.albedoTexture.hasAlpha = true;
  78482. babylonMaterial.useAlphaFromAlbedoTexture = true;
  78483. }
  78484. break;
  78485. default:
  78486. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  78487. }
  78488. };
  78489. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  78490. var _this = this;
  78491. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  78492. if (!sampler) {
  78493. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  78494. }
  78495. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  78496. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  78497. this._addPendingData(texture);
  78498. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  78499. _this._tryCatchOnError(function () {
  78500. _this._removePendingData(texture);
  78501. });
  78502. }, function (message) {
  78503. _this._tryCatchOnError(function () {
  78504. throw new Error(context + ": " + message);
  78505. });
  78506. });
  78507. if (texture.url) {
  78508. babylonTexture.updateURL(texture.url);
  78509. }
  78510. else if (texture.dataReadyObservable) {
  78511. texture.dataReadyObservable.add(function (texture) {
  78512. babylonTexture.updateURL(texture.url);
  78513. });
  78514. }
  78515. else {
  78516. texture.dataReadyObservable = new BABYLON.Observable();
  78517. texture.dataReadyObservable.add(function (texture) {
  78518. babylonTexture.updateURL(texture.url);
  78519. });
  78520. var image_1 = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  78521. if (!image_1) {
  78522. throw new Error(context + ": Failed to find source " + texture.source);
  78523. }
  78524. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  78525. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  78526. if (texture.dataReadyObservable) {
  78527. texture.dataReadyObservable.notifyObservers(texture);
  78528. }
  78529. });
  78530. }
  78531. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  78532. if (sampler.wrapS !== undefined) {
  78533. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  78534. }
  78535. if (sampler.wrapT !== undefined) {
  78536. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  78537. }
  78538. babylonTexture.name = texture.name || "texture" + texture.index;
  78539. if (this._parent.onTextureLoaded) {
  78540. this._parent.onTextureLoaded(babylonTexture);
  78541. }
  78542. return babylonTexture;
  78543. };
  78544. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  78545. if (image.uri) {
  78546. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  78547. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  78548. }
  78549. else {
  78550. this._loadUri(context, image.uri, onSuccess);
  78551. }
  78552. }
  78553. else {
  78554. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  78555. if (!bufferView) {
  78556. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  78557. }
  78558. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  78559. }
  78560. };
  78561. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  78562. var _this = this;
  78563. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  78564. throw new Error(context + ": Uri '" + uri + "' is invalid");
  78565. }
  78566. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  78567. _this._tryCatchOnError(function () {
  78568. onSuccess(new Uint8Array(data));
  78569. });
  78570. }, function (event) {
  78571. _this._tryCatchOnError(function () {
  78572. _this._onProgress(event);
  78573. });
  78574. }, this._babylonScene.database, true, function (request) {
  78575. _this._tryCatchOnError(function () {
  78576. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  78577. });
  78578. });
  78579. if (request) {
  78580. this._requests.push(request);
  78581. }
  78582. };
  78583. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  78584. try {
  78585. handler();
  78586. }
  78587. catch (e) {
  78588. this._onError(e.message);
  78589. }
  78590. };
  78591. GLTFLoader.Extensions = {};
  78592. return GLTFLoader;
  78593. }());
  78594. GLTF2.GLTFLoader = GLTFLoader;
  78595. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  78596. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78597. })(BABYLON || (BABYLON = {}));
  78598. //# sourceMappingURL=babylon.glTFLoader.js.map
  78599. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78600. var BABYLON;
  78601. (function (BABYLON) {
  78602. var GLTF2;
  78603. (function (GLTF2) {
  78604. /**
  78605. * Utils functions for GLTF
  78606. */
  78607. var GLTFUtils = /** @class */ (function () {
  78608. function GLTFUtils() {
  78609. }
  78610. /**
  78611. * If the uri is a base64 string
  78612. * @param uri: the uri to test
  78613. */
  78614. GLTFUtils.IsBase64 = function (uri) {
  78615. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  78616. };
  78617. /**
  78618. * Decode the base64 uri
  78619. * @param uri: the uri to decode
  78620. */
  78621. GLTFUtils.DecodeBase64 = function (uri) {
  78622. var decodedString = atob(uri.split(",")[1]);
  78623. var bufferLength = decodedString.length;
  78624. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  78625. for (var i = 0; i < bufferLength; i++) {
  78626. bufferView[i] = decodedString.charCodeAt(i);
  78627. }
  78628. return bufferView.buffer;
  78629. };
  78630. GLTFUtils.ValidateUri = function (uri) {
  78631. return (uri.indexOf("..") === -1);
  78632. };
  78633. GLTFUtils.AssignIndices = function (array) {
  78634. if (array) {
  78635. for (var index = 0; index < array.length; index++) {
  78636. array[index].index = index;
  78637. }
  78638. }
  78639. };
  78640. GLTFUtils.GetArrayItem = function (array, index) {
  78641. if (!array || !array[index]) {
  78642. return null;
  78643. }
  78644. return array[index];
  78645. };
  78646. GLTFUtils.GetTextureWrapMode = function (mode) {
  78647. // Set defaults if undefined
  78648. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  78649. switch (mode) {
  78650. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  78651. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  78652. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  78653. default:
  78654. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  78655. return BABYLON.Texture.WRAP_ADDRESSMODE;
  78656. }
  78657. };
  78658. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  78659. // Set defaults if undefined
  78660. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  78661. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  78662. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  78663. switch (minFilter) {
  78664. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  78665. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  78666. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  78667. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  78668. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  78669. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  78670. default:
  78671. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  78672. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  78673. }
  78674. }
  78675. else {
  78676. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  78677. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  78678. }
  78679. switch (minFilter) {
  78680. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  78681. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  78682. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  78683. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  78684. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  78685. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  78686. default:
  78687. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  78688. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  78689. }
  78690. }
  78691. };
  78692. return GLTFUtils;
  78693. }());
  78694. GLTF2.GLTFUtils = GLTFUtils;
  78695. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78696. })(BABYLON || (BABYLON = {}));
  78697. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  78698. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78699. var BABYLON;
  78700. (function (BABYLON) {
  78701. var GLTF2;
  78702. (function (GLTF2) {
  78703. var GLTFLoaderExtension = /** @class */ (function () {
  78704. function GLTFLoaderExtension() {
  78705. this.enabled = true;
  78706. }
  78707. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  78708. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  78709. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  78710. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  78711. var _this = this;
  78712. if (!property.extensions) {
  78713. return false;
  78714. }
  78715. var extension = property.extensions[this.name];
  78716. if (!extension) {
  78717. return false;
  78718. }
  78719. // Clear out the extension before executing the action to avoid recursing into the same property.
  78720. property.extensions[this.name] = undefined;
  78721. action(extension, function () {
  78722. // Restore the extension after completing the action.
  78723. if (property.extensions) {
  78724. property.extensions[_this.name] = extension;
  78725. }
  78726. });
  78727. return true;
  78728. };
  78729. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  78730. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  78731. };
  78732. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  78733. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  78734. };
  78735. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  78736. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  78737. };
  78738. GLTFLoaderExtension._ApplyExtensions = function (action) {
  78739. var extensions = GLTFLoaderExtension._Extensions;
  78740. if (!extensions) {
  78741. return false;
  78742. }
  78743. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  78744. var extension = extensions_1[_i];
  78745. if (extension.enabled && action(extension)) {
  78746. return true;
  78747. }
  78748. }
  78749. return false;
  78750. };
  78751. //
  78752. // Utilities
  78753. //
  78754. GLTFLoaderExtension._Extensions = [];
  78755. return GLTFLoaderExtension;
  78756. }());
  78757. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  78758. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78759. })(BABYLON || (BABYLON = {}));
  78760. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  78761. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  78762. var BABYLON;
  78763. (function (BABYLON) {
  78764. var GLTF2;
  78765. (function (GLTF2) {
  78766. var Extensions;
  78767. (function (Extensions) {
  78768. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  78769. var MSFTLOD = /** @class */ (function (_super) {
  78770. __extends(MSFTLOD, _super);
  78771. function MSFTLOD() {
  78772. return _super !== null && _super.apply(this, arguments) || this;
  78773. }
  78774. Object.defineProperty(MSFTLOD.prototype, "name", {
  78775. get: function () {
  78776. return "MSFT_lod";
  78777. },
  78778. enumerable: true,
  78779. configurable: true
  78780. });
  78781. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  78782. return this._loadExtension(node, function (extension, onComplete) {
  78783. if (!loader._gltf.nodes) {
  78784. return;
  78785. }
  78786. for (var i = extension.ids.length - 1; i >= 0; i--) {
  78787. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  78788. if (!lodNode) {
  78789. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  78790. }
  78791. loader._traverseNode(context, lodNode, action, parentNode);
  78792. }
  78793. loader._traverseNode(context, node, action, parentNode);
  78794. onComplete();
  78795. });
  78796. };
  78797. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  78798. var _this = this;
  78799. return this._loadExtension(node, function (extension, onComplete) {
  78800. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  78801. loader._addLoaderPendingData(node);
  78802. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  78803. loader._removeLoaderPendingData(node);
  78804. onComplete();
  78805. });
  78806. });
  78807. };
  78808. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  78809. var _this = this;
  78810. loader._whenAction(function () {
  78811. loader._loadNode(context, nodes[index]);
  78812. }, function () {
  78813. if (index !== nodes.length - 1) {
  78814. var previousNode = nodes[index + 1];
  78815. if (previousNode.babylonMesh) {
  78816. previousNode.babylonMesh.setEnabled(false);
  78817. }
  78818. }
  78819. if (index === 0) {
  78820. onComplete();
  78821. return;
  78822. }
  78823. setTimeout(function () {
  78824. loader._tryCatchOnError(function () {
  78825. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  78826. });
  78827. }, MSFTLOD.MinimalLODDelay);
  78828. });
  78829. };
  78830. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  78831. var _this = this;
  78832. return this._loadExtension(material, function (extension, onComplete) {
  78833. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  78834. loader._addLoaderPendingData(material);
  78835. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  78836. if (material.extensions) {
  78837. material.extensions[_this.name] = extension;
  78838. }
  78839. loader._removeLoaderPendingData(material);
  78840. onComplete();
  78841. });
  78842. });
  78843. };
  78844. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  78845. var _this = this;
  78846. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  78847. assign(babylonMaterial, isNew);
  78848. if (index === 0) {
  78849. onComplete();
  78850. return;
  78851. }
  78852. // Load the next LOD when the loader is ready to render and
  78853. // all active material textures of the current LOD are loaded.
  78854. loader._executeWhenRenderReady(function () {
  78855. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  78856. setTimeout(function () {
  78857. loader._tryCatchOnError(function () {
  78858. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  78859. });
  78860. }, MSFTLOD.MinimalLODDelay);
  78861. });
  78862. });
  78863. });
  78864. };
  78865. /**
  78866. * Specify the minimal delay between LODs in ms (default = 250)
  78867. */
  78868. MSFTLOD.MinimalLODDelay = 250;
  78869. return MSFTLOD;
  78870. }(GLTF2.GLTFLoaderExtension));
  78871. Extensions.MSFTLOD = MSFTLOD;
  78872. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  78873. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  78874. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78875. })(BABYLON || (BABYLON = {}));
  78876. //# sourceMappingURL=MSFT_lod.js.map
  78877. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  78878. var BABYLON;
  78879. (function (BABYLON) {
  78880. var GLTF2;
  78881. (function (GLTF2) {
  78882. var Extensions;
  78883. (function (Extensions) {
  78884. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  78885. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  78886. function KHRMaterialsPbrSpecularGlossiness() {
  78887. return _super !== null && _super.apply(this, arguments) || this;
  78888. }
  78889. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  78890. get: function () {
  78891. return "KHR_materials_pbrSpecularGlossiness";
  78892. },
  78893. enumerable: true,
  78894. configurable: true
  78895. });
  78896. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  78897. var _this = this;
  78898. return this._loadExtension(material, function (extension, onComplete) {
  78899. loader._createPbrMaterial(material);
  78900. loader._loadMaterialBaseProperties(context, material);
  78901. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  78902. if (material.babylonMaterial) {
  78903. assign(material.babylonMaterial, true);
  78904. }
  78905. });
  78906. };
  78907. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  78908. var babylonMaterial = material.babylonMaterial;
  78909. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  78910. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  78911. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  78912. if (loader._gltf.textures) {
  78913. if (properties.diffuseTexture) {
  78914. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  78915. if (!texture) {
  78916. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  78917. }
  78918. if (properties.diffuseTexture.texCoord) {
  78919. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  78920. }
  78921. }
  78922. if (properties.specularGlossinessTexture) {
  78923. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  78924. if (!texture) {
  78925. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  78926. }
  78927. if (properties.specularGlossinessTexture.texCoord) {
  78928. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  78929. }
  78930. babylonMaterial.reflectivityTexture.hasAlpha = true;
  78931. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  78932. }
  78933. }
  78934. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  78935. };
  78936. return KHRMaterialsPbrSpecularGlossiness;
  78937. }(GLTF2.GLTFLoaderExtension));
  78938. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  78939. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  78940. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  78941. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78942. })(BABYLON || (BABYLON = {}));
  78943. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  78944. (function universalModuleDefinition(root, factory) {
  78945. if (root && root["BABYLON"]) {
  78946. return;
  78947. }
  78948. if(typeof exports === 'object' && typeof module === 'object')
  78949. module.exports = factory();
  78950. else if(typeof define === 'function' && define.amd)
  78951. define([], factory);
  78952. else if(typeof exports === 'object')
  78953. exports["BABYLON"] = factory();
  78954. else {
  78955. root["BABYLON"] = factory();
  78956. }
  78957. })(this, function() {
  78958. return BABYLON;
  78959. });